Quiz that changes section depending on the answer

Asked

Viewed 264 times

-2

I’m developing a quiz with , which has to work as follows, has the question and response feedback, but then I go to another section where there’s a story and only then comes another question.

My question is the following between a question and another can I put a section with a text? I’m doing the questions with array, I’ll show you an example of how it is so far.

var questao1 = {
  questao: '<span>1.</span> Assinale a alternativa correta”',
  alternativas: ['a) Dependente; B.', 'b) Independente; B', 'c) Independente; T.'],
  correta: 2
};
var questao2 = {
  questao: '<span>2.</span> Quais são os sitomas mais comuns da doença meningocócica?',
  alternativas: ['a) Febre, mal-estar geral, dores musculares, vômitos, diarreia e dor de cabeça.', 'b) Mal-estar,diarreia, vômitos, calafrio, dor nos braços e nas pernas.', 'c) Dor de cabeça, nauseas e vômitos, intolerancia a luz e ruidos, manchas amarelas na pele.'],
  correta: 0
};

var questoes = [questao1, questao2];


// Váriaveis globais
var tags;
var tagsClass = '';
var liTagsid = [];
var alternativaCorreta = 0;
var quizPage = 1;
var index = 0;
var questaoAtual = questoes[index];
var questaoAnterior;
var indexAnterior = 0;
var ulTag = document.getElementsByTagName('ul')[0];
var botao = document.getElementById('responder');
var tituloQuestao = document.getElementById('questao');
var selecionada = 'selected';

function showQuestions() {
  if (index != 0) {
    // cria o botão de responder nas próximas páginas
    ulTag.innerHTML = '';
    botao.innerHTML = 'Responder';
    botao.className = 'responder btn';
    botao.id = 'responder';
    document.getElementById('numeroQuiz').innerHTML = quizPage;
  }

  //Mostra o resultado no final da página
  if (index == (questoes.length)) {
    ulTag.innerHTML = '';
    // document.getElementById('question').innerHTML = '';
    // showResults();

    var url = window.location.href;
    var absoluto = url.split("/")[url.split("/").length - 1];
    // alert(absoluto);
    if (absoluto == 'tela03.html') {
      window.location.href = 'tela04.html';
    } else if (absoluto == 'tela05.html') {
      window.location.href = 'tela06.html';
    } else if (absoluto == 'tela07.html') {
      window.location.href = 'tela08.html';
    } else if (absoluto == 'tela09.html') {
      window.location.href = 'tela10.html';
    }
    return
  }

  tituloQuestao.innerHTML = questaoAtual.questao;
  console.log(questaoAtual.questao);

  // gera as alternativas
  for (var i = 0; i < questaoAtual.alternativas.length; i++) {
    var newAlt = document.createElement('li');
    newAlt.id = 'alt' + (i + 1);
    newAlt.className = "notSelected";
    var textAlt = document.createTextNode(questaoAtual.alternativas[i]);
    newAlt.appendChild(textAlt);
    var addNewAltHere = document.getElementById('alternativa');
    addNewAltHere.appendChild(newAlt);
    console.log(questaoAtual.alternativas[i]);
  }
  var $liTags = $('.notSelected').click(function(list) {
    list.preventDefault();
    $liTags.removeClass(selecionada);
    $(this).addClass(selecionada);
    for (var i = 0; i < questaoAtual.alternativas.length; i++) {
      // console.log(liTagsid[i]);
      if ($liTags[i].className == "notSelected selected") {
        //armazena a alternativa
        tags = $liTags[i].id;
        // tagsClass = $LiTags.className;
        console.log(tags);
        tagsClassName = $liTags[i];
      }
    }
  });
  botao.onclick = function() {
    checkAnswer()
  };
}

showQuestions();

function checkAnswer() {
  var selectedItem = document.getElementById(tags);

  // Caso não tenha escolhido alguma alternativa
  if (selectedItem == undefined) {
    alert("Por favor selecione uma alternativa.")
    return
  } else {
    var userAns = selectedItem.innerHTML;
  }
  // muda o background de acordo com a escolha
  if (userAns == questaoAtual.alternativas[questaoAtual.correta]) {
    console.log("Acertou: " + userAns);
    $('#modalAcertou').modal();
    selectedItem.className = 'correta';
    alternativaCorreta++;
    console.log(alternativaCorreta);
    $('.notSelected').addClass('disabled');
  } else {
    console.log("Errou a alternativa correta é : " + questaoAtual.alternativas[questaoAtual.correta]);
    $('#modalErrou').modal();
    return
    selectedItem.className = 'wrong';
    ulTag.getElementsByTagName('li')[questaoAtual.correta].className = 'correta';
    console.log(questaoAtual.alternativas[questaoAtual.correta]);
  }

  // Cria o botão para a próxima pergunta após responder certo
  botao.innerHTML = 'Próxima Pergunta';
  botao.className = 'next btn';
  botao.id = 'next';
  questaoAnterior = questaoAtual;
  quizPage++;
  index++;
  questaoAtual = questoes[index];

  botao.onclick = function() {
    showQuestions()
  };
  return
}
#fundo-externo {
  overflow: hidden;
  /* para que não tenha rolagem se a imagem de fundo for maior que a tela */
  width: 100%;
  height: 100%;
  position: relative;
  /* criamos um contexto para posicionamento */
}

#fundo {
  position: fixed;
  /* posição fixa para que a possível rolagem da tela não revele espaços em branco */
  width: 100%;
  height: 100%;
  z-index: -1;
}

#fundo img {
  width: 100%;
  /* com isso imagem ocupará toda a largura da tela. Se colocarmos height: 100% também, a imagem irá distorcer */
  position: absolute;
}

#pagina-quiz {
  background-color: white;
  margin: 0 auto;
  width: 80%;
  margin-top: 30px;
  padding: 30px;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}

#pagina-quiz p,
#pagina-quiz li,
.wrapper {
  color: #6d6d6d;
  font-size: 18px;
  line-height: 22px;
}

.wrapper {
  margin: 15px 0;
}

#pagina-quiz li {
  list-style-type: none;
  text-align: left;
  background-color: transparent;
  margin: 10px 5px;
  padding: 15px 10px;
  border-top: 1px solid #ecedee;
  border-bottom: 1px solid #ecedee;
  font-weight: normal;
  cursor: pointer;
}


/*#pagina-quiz li:hover{
    background: #ECEEF0;
}*/

#question p span {
  color: #898655;
}

#pagina-quiz .selected,
.selected:hover {
  background: #FFDEAD;
}

#pagina-quiz .correta {
  /*background: #bec8a3;*/
  background: #00ff0080;
  color: white;
}

#pagina-quiz .wrong,
.wrong:hover {
  background: #d49274;
  color: white;
}

.button {
  text-align: right;
  margin-top: 55px;
}


/*.submit:hover, .submit:active, .submit:focus {
    background: #43A047;
}*/

.responder {
  background: #fff;
  min-width: 120px;
}

.next {
  background: #fa994a;
  min-width: 120px;
  color: #fff;
}

.next:hover,
.next:active,
.next:focus {
  background: #e38a42;
}

.restart {
  background-color:
}

canvas {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 0;
  border: 0px solid #000;
}

.modal-header {
  border-bottom: 0;
}

.disabled {
  pointer-events: none;
  opacity: 0.6;
}

.modal-content {
  border-radius: 10px;
  visibility: visible;
  background: rgb(23, 116, 15);
  transform: matrix(1, 0, 0, 1, 0, 0);
}

#modalErrou .modal-content {
  background: #e60000;
}

.modal-content h1 {
  font-size: 42px;
  color: #ffffff;
}

#pagina-quiz .modal-content .modal-body p {
  font-size: 19px;
  color: #ffffff;
}

#pagina-quiz .modal-content span {
  color: #fff
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<main id="bkgTelas">
  <div id="pagina-quiz">
    <div class="container">
      <!-- Modal -->
      <div class="modal fade" id="modalAcertou" tabindex="-1" role="dialog" aria-labelledby="modalAcertouTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h1>Parabéns</h1>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
						          <span aria-hidden="true">&times;</span>
						        </button>
            </div>
            <div class="modal-body">
              <p>A resposta está correta.</p>
            </div>
          </div>
        </div>
      </div>
      <div class="modal fade" id="modalErrou" tabindex="-1" role="dialog" aria-labelledby="modalErrouTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h1>Atenção!</h1>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
						          <span aria-hidden="true">&times;</span>
						        </button>
            </div>
            <div class="modal-body">
              <p>Você selecionou a resposta errada.</p>
              <p>Tente novamente.</p>
            </div>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <div class="wrapper" id="pages">
            <span id="numeroQuiz">1</span><span>/20</span>
          </div>
        </div>
        <div class="col-12">
          <div class="quiz-questions" id="display-area">
            <p id="questao"></p>
            <ul id="alternativa"></ul>
            <div id="quiz-resultados" style="text-align: center;">
              <button type="button" name="button" class="responder btn" id="responder">Confirmar</button>
            </div>
          </div>
        </div>
      </div>
      <canvas id="canvas"></canvas>
    </div>
  </div>
</main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

2 answers

1


Hello,

See if that’s what you’re looking for: Here

I added the changes you need:

  • I added another property to the question object called texto.

In each object statement you can now include the explanatory text you would like to show after the question.

  • I created the functions showText(texto) and showQuestionLayer()

These functions only control the display of your issue in html, the showText also receives the text you would like to be displayed by parameter.

  • I created a new div in your html code

That one div allows the content to be available to be shown when the question is answered, this was the code snippet that I entered:

<div class="container" id="texto" style="display: none">
   <div id="conteudo_texto" style="margin-bottom: 10px;"></div>
   <button
     type="button"
     name="button"
     class="next btn"
     onclick="showQuestionLayer()"
   >
     Próxima Pergunta
   </button>
 </div>

With these changes apparently your problem is solved.

PS. There are better ways to write your code, I just followed your pattern, however I advise to study a little more of how jQuery works and add events from the jQuery.ready() this will make your code more readable and within jQuery conventions. Just a hint.

0

You can use the visibility properties. For example:

document.getElementById("myP").style.visibility = "hidden";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.