0

So I want to make a quiz on html document. All good till I verify every question if the answer was correct or wrong.

If the answer of the question is correct I want to change the answer(button text) on green or else in red. The thing is that I show only 1 question at the time but the color update is only made after the next question appears. Is it because the document changes will happen only after the function ends? The html code is simple:

 
function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
        end = new Date().getTime();
    }
}


function Quiz(questions) {
    this.score = 0;
    this.questions = questions;
    this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
    return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
    if(this.getQuestionIndex().isCorrectAnswer(answer)) {
        console.log(answer);

        this.score++;
    }

    for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
        var number =this.getQuestionIndex().getCorrectAnswer().charCodeAt(0)-65;
        if (i===number)
            document.getElementById("btn"+ i).style.color="green";
        else
            document.getElementById("btn"+ i).style.color="red";

    }

    this.questionIndex++;
}



Quiz.prototype.isEnded = function() {
    return this.questionIndex === this.questions.length;
}


function Question(text, textAnswer, choices, answer) {
    this.text = text;
    this.textAnswer = textAnswer;
    this.choices = choices;
    this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {

    return this.answer === choice;

}
Question.prototype.getCorrectAnswer= function(){
    return this.answer

}


function populate() {
    if(quiz.isEnded()) {
        showScores();
    }
    else {
        // show question
        var element = document.getElementById("question");
        element.innerHTML = quiz.getQuestionIndex().text;


        // show textAnswer
        var textAnswer = quiz.getQuestionIndex().textAnswer;
        for(var i = 0; i < textAnswer.length; i++) {
            var element = document.getElementById("textAnswer" + i);
            element.innerHTML = textAnswer[i];
        }

        // show options
        var choices = quiz.getQuestionIndex().choices;
        for(var i = 0; i < choices.length; i++) {
            var element = document.getElementById("choice" + i);
            element.innerHTML = choices[i];
            guess("btn" + i, choices[i]);

        }

        showProgress();
    }
};


function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
        quiz.guess(guess);

        populate();

    }
};


function showProgress() {
    var currentQuestionNumber = quiz.questionIndex + 1;
    var element = document.getElementById("progress");
    element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
    var gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
    var element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
};

// create questions here
var questions = [
    new Question("1.Cum sunt semnalizate benzile de circulație reversibilă, care vă permit să continuați deplasarea?",
        ["A: cu dispozitive de culoare galbenă intermitentă",
            "B: cu semnul roșu în cruce",
            "C: cu semnalul verde de forma unei săgeți cu vârful în jos"],
        ["A", "B","C"],
        "C"),
    new Question("2.Precizați care dintre indicatoarele de mai jos indică o cale rutieră cu sens unic: <br> <img class='image' src='Test/7533.jpg' /> </br>",
        ["A: indicatorul 1",
            "B: indicatorul 2",
            "C: ambele indicatoare"],
        ["A", "B","C"],
        "C"),
    new Question("3.Ce semnifică indicatorul din imagine? <br> <img class='image' src='Test/3615.jpg' /> </br>",
        ["A: Accesul interzis copiilor neînsoțiți",
            "B: Trecere obligatorie pentru copii",
            "C: Copii"],
        ["A", "B","C"],
        "C"),
    new Question("4.Ce semnificație are un astfel de marcaj rutier? <br> <img class='image' src='Test/3687.jpg' /> </br>",
        ["A: marcaj pentru spații interzise",
            "B: marcaj pe o bandă de decelerare",
            "C: deviere temporară a circulației"],
        ["A", "B","C"],
        "B"),
    new Question("5.Ce semnificație are indicatorul din imagine? <br> <img class='image' src='Test/3659.jpg' /> </br>",
        ["A: urmează un sector de drum îngustat temporar",
            "B: urmează o intersecție cu un drum fără prioritate",
            "C: este interzisă schimbarea direcției de mers la dreapta în prima intersecție"],
        ["A", "B","C"],
        "B"),
    new Question("6.Ce semnificație are marcajul rutier din imagine? <br> <img class='image' src='Test/3589.jpg' /> </br>",
        ["A: spațiu pentru oprirea în caz de urgență",
            "B: marcaj transversal de oprire",
            "C: bandă de circulație destinată opririi voluntare"],
        ["A", "B","C"],
        "B"),
    new Question("7.Ce obligații revin conducătorilor la întâlnirea indicatorului? <br> <img class='image' src='Test/3438.jpg' /> </br>",
        ["A: să acorde prioritate vehiculelor care circulă în intersecție",
            "B: să acorde prioritate de dreapta",
            "C: să ocolească centrul intersecției și să circule cât mai aproape de marginea străzii"],
        ["A", "B","C"],
        "A"),
    new Question("8.Care este semnificația indicatorului? <br> <img class='image' src='Test/3601.jpg' /> </br>",
        ["A: obligă la ocolirea prin dreapta a locului unde este instalat",
            "B: obligă la schimbarea direcției de mers către dreapta",
            "C: obligă la folosirea benzii de lângă trotuar"],
        ["A", "B","C"],
        "A"),
    new Question("9.Indicatorul alăturat reprezintă: <br> <img class='image' src='Test/9509.jpg' /> </br>",
        ["A: panouri succesive pentru curbe deosebit de periculoase",
            "B: panou suplimentar, montat la 150 m față de calea ferată",
            "C: baliză bidirecțională care indică ocolirea obstacolului prin stânga sau prin dreapta"],
        ["A", "B","C"],
        "C"),
    new Question("10.Cum vei proceda la întâlnirea indicatorului „Limitare de viteză 80 km/h”? <br> <img class='image' src='Test/3615.jpg' /> </br>",
        ["A: nu depășești viteza maximă admisă pe drumurile naționale",
            "B: nu depășești viteza de 80 km/h",
            "C: circuli cu o viteză de peste 80 km/h"],
        ["A", "B","C"],
        "B")
];

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Quiz</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="grid">
        <div id="quiz">
            <h1>Quiz</h1>
            <hr style="margin-bottom: 20px">

            <p id="question"></p>

            <ul class="grid1">
                <li id="textAnswer0"></li>
                <li id="textAnswer1"></li>
                <li id="textAnswer2"></li>
            </ul>

            <div class="buttons">
                <button id="btn0"><span id="choice0"></span></button>
                <button id="btn1"><span id="choice1"></span></button>
                <button id="btn2"><span id="choice2"></span></button>
            </div>
             <span id="wrong_answer"></span>
            <hr style="margin-top: 50px">
            <footer>
                <p id="progress">Question x of y</p>
            </footer>
        </div>
    </div>

 
</body>
</html>

What I want is after every click on any of A B or C to show which one is wrong /correct , wait like 3 seconds and go to the next question.

Viney
  • 6,629
  • 3
  • 21
  • 40
  • 2
    Not entirely sure what the question is. If you are asking if the browser waits for a function to end before updating the dom, no. The DOM can be updated while a function executes. However, the browser does not immediately rebuild the display when you edit the DOM. It has to be given a chance to do so. – Taplar May 15 '20 at 16:01
  • That's way too much code (-> [mcve]) and a terrible version of ["wait" function](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep). – Andreas May 15 '20 at 16:07
  • The wait function I got from that link since js doesn't have one implemented. – Ilie Iulian Cotiuga May 15 '20 at 17:55

1 Answers1

0

Your code has no issue related with javascript's particularity, rather it's you code where you call function to display the next question in the same function in which you reveal the answer

You need to add some way user to navigate to next question when you reveal him the answer to current question

I have added <button onclick="populate();" id="nxtbtn">Next</button> for that

function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
        end = new Date().getTime();
    }
}


function Quiz(questions) {
    this.score = 0;
    this.questions = questions;
    this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
    return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
    if(this.getQuestionIndex().isCorrectAnswer(answer)) {
        console.log(answer);

        this.score++;
    }

    for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
        var number =this.getQuestionIndex().getCorrectAnswer().charCodeAt(0)-65;
        if (i===number)
            document.getElementById("btn"+ i).style.color="green";
        else
            document.getElementById("btn"+ i).style.color="red";

    }

    this.questionIndex++;
 document.getElementById('nxtbtn').disabled = false;
}



Quiz.prototype.isEnded = function() {
    return this.questionIndex === this.questions.length;
}


function Question(text, textAnswer, choices, answer) {
    this.text = text;
    this.textAnswer = textAnswer;
    this.choices = choices;
    this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {

    return this.answer === choice;

}
Question.prototype.getCorrectAnswer= function(){
    return this.answer

}


function populate() {
    if(quiz.isEnded()) {
  document.getElementById('nxtbtn').style.display = 'none';
        showScores();
    }
    else {
        // show question
        var element = document.getElementById("question");
        element.innerHTML = quiz.getQuestionIndex().text;


        // show textAnswer
        var textAnswer = quiz.getQuestionIndex().textAnswer;
        for(var i = 0; i < textAnswer.length; i++) {
            var element = document.getElementById("textAnswer" + i);
            element.innerHTML = textAnswer[i];
        }

        // show options
        var choices = quiz.getQuestionIndex().choices;
        for(var i = 0; i < choices.length; i++) {
            var element = document.getElementById("choice" + i);
            element.innerHTML = choices[i];
            guess("btn" + i, choices[i]);

        }

        showProgress();
  
  for(var i = 0; i < quiz.getQuestionIndex().choices.length; i++) {
    document.getElementById("btn"+ i).style.color="inherit";
  }
  document.getElementById('nxtbtn').disabled = true;
    }
};


function guess(id, guess) {
    var button = document.getElementById(id);
    button.onclick = function() {
        quiz.guess(guess);
    }
};


function showProgress() {
    var currentQuestionNumber = quiz.questionIndex + 1;
    var element = document.getElementById("progress");
    element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
    var gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
    var element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
};

// create questions here
var questions = [
    new Question("1.Cum sunt semnalizate benzile de circulație reversibilă, care vă permit să continuați deplasarea?",
        ["A: cu dispozitive de culoare galbenă intermitentă",
            "B: cu semnul roșu în cruce",
            "C: cu semnalul verde de forma unei săgeți cu vârful în jos"],
        ["A", "B","C"],
        "C"),
    new Question("2.Precizați care dintre indicatoarele de mai jos indică o cale rutieră cu sens unic: <br> <img class='image' src='Test/7533.jpg' /> </br>",
        ["A: indicatorul 1",
            "B: indicatorul 2",
            "C: ambele indicatoare"],
        ["A", "B","C"],
        "C"),
    new Question("3.Ce semnifică indicatorul din imagine? <br> <img class='image' src='Test/3615.jpg' /> </br>",
        ["A: Accesul interzis copiilor neînsoțiți",
            "B: Trecere obligatorie pentru copii",
            "C: Copii"],
        ["A", "B","C"],
        "C"),
    new Question("4.Ce semnificație are un astfel de marcaj rutier? <br> <img class='image' src='Test/3687.jpg' /> </br>",
        ["A: marcaj pentru spații interzise",
            "B: marcaj pe o bandă de decelerare",
            "C: deviere temporară a circulației"],
        ["A", "B","C"],
        "B"),
    new Question("5.Ce semnificație are indicatorul din imagine? <br> <img class='image' src='Test/3659.jpg' /> </br>",
        ["A: urmează un sector de drum îngustat temporar",
            "B: urmează o intersecție cu un drum fără prioritate",
            "C: este interzisă schimbarea direcției de mers la dreapta în prima intersecție"],
        ["A", "B","C"],
        "B"),
    new Question("6.Ce semnificație are marcajul rutier din imagine? <br> <img class='image' src='Test/3589.jpg' /> </br>",
        ["A: spațiu pentru oprirea în caz de urgență",
            "B: marcaj transversal de oprire",
            "C: bandă de circulație destinată opririi voluntare"],
        ["A", "B","C"],
        "B"),
    new Question("7.Ce obligații revin conducătorilor la întâlnirea indicatorului? <br> <img class='image' src='Test/3438.jpg' /> </br>",
        ["A: să acorde prioritate vehiculelor care circulă în intersecție",
            "B: să acorde prioritate de dreapta",
            "C: să ocolească centrul intersecției și să circule cât mai aproape de marginea străzii"],
        ["A", "B","C"],
        "A"),
    new Question("8.Care este semnificația indicatorului? <br> <img class='image' src='Test/3601.jpg' /> </br>",
        ["A: obligă la ocolirea prin dreapta a locului unde este instalat",
            "B: obligă la schimbarea direcției de mers către dreapta",
            "C: obligă la folosirea benzii de lângă trotuar"],
        ["A", "B","C"],
        "A"),
    new Question("9.Indicatorul alăturat reprezintă: <br> <img class='image' src='Test/9509.jpg' /> </br>",
        ["A: panouri succesive pentru curbe deosebit de periculoase",
            "B: panou suplimentar, montat la 150 m față de calea ferată",
            "C: baliză bidirecțională care indică ocolirea obstacolului prin stânga sau prin dreapta"],
        ["A", "B","C"],
        "C"),
    new Question("10.Cum vei proceda la întâlnirea indicatorului „Limitare de viteză 80 km/h”? <br> <img class='image' src='Test/3615.jpg' /> </br>",
        ["A: nu depășești viteza maximă admisă pe drumurile naționale",
            "B: nu depășești viteza de 80 km/h",
            "C: circuli cu o viteză de peste 80 km/h"],
        ["A", "B","C"],
        "B")
];

// create quiz
var quiz = new Quiz(questions);

// display quiz
populate();
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Quiz</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="grid">
        <div id="quiz">
            <h1>Quiz</h1>
            <hr style="margin-bottom: 20px">

            <p id="question"></p>

            <ul class="grid1">
                <li id="textAnswer0"></li>
                <li id="textAnswer1"></li>
                <li id="textAnswer2"></li>
            </ul>

            <div class="buttons">
                <button id="btn0"><span id="choice0"></span></button>
                <button id="btn1"><span id="choice1"></span></button>
                <button id="btn2"><span id="choice2"></span></button>
            </div>
   
            <div>
                 <button onclick="populate();" id="nxtbtn">Next</button>
            </div>
             <span id="wrong_answer"></span>
            <hr style="margin-top: 50px">
            <footer>
                <p id="progress">Question x of y</p>
            </footer>
        </div>
    </div>

 
</body>
</html>
Viney
  • 6,629
  • 3
  • 21
  • 40
  • If I do that I will have to freeze those 3 buttons so the man that takes the quiz wont be able to change the answer after is revealed. Thank you for your fast reply. – Ilie Iulian Cotiuga May 15 '20 at 17:37