-2

I have made a little quiz using JS, HTML and CSS. Am using "addEventListener" but it is not working properly and I don't know how to fix it. I have seen other have ask a similar question but none of them solve my problem. I think it should be easy to understand my code. Also if you see any other issues with my code please let me know.

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)) {
        this.score++;
    }

    this.questionIndex++;
}

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


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

Question.prototype.isCorrectAnswer = function(choice) {
    return this.answer === choice;
}


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

        // 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 shuffle_questions(questions) {
    var currentIndex = questions.length, temporaryValue, randomIndex;

    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        temporaryValue = questions[currentIndex];
        questions[currentIndex] = questions[randomIndex];
        questions[randomIndex] = temporaryValue;
    }

    return questions;
}

function restart() {
    document.getElementById("quiz").innerHTML = ''; // Clear out the "game over"
    questions = shuffle_questions(questions); // Left as an exercise for the reader; see https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    quiz = new Quiz(questions); // Rebuild the quiz object
    populate();
  
    return false; // So the link doesn't try to go anywhere
  }

function showScores() {
    var gameOverHTML = "<h1>Result</h1>";
    gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
    // message if they would like to try again
    gameOverHTML += gameOverHTML.addEventListener("click", restart); //not done yet
    var element = document.getElementById("quiz");
    element.innerHTML = gameOverHTML;
};

// create questions here
var questions = [
    new Question("Which nation won FIFA 2018 World Cup?", ["Peru", "France","Germany", "USA"], "France"),
    new Question("Which nation hosted FIFA 2018 World Cup?", ["Sweden", "Russia", "Iran", "South Korea"], "Russia"),
    new Question("Which nation has won the most World Cups?", ["Argentina", "Peru","Brazil", "France"], "Brazil"),
    new Question("Where was FIFA 2014 World Cup hosted?", ["Ecuador", "Brazil", "France", "All"], "Brazil"),
    new Question("Which nation won the first FIFA World Cup", ["Brazil", "Uruguay", "Italy", "Australia"], "Uruguay")
];

// 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>FIFA World Cup Quiz</h1>
            <hr style="margin-bottom: 20px">

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

            <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>
                <button id="btn3"><span id="choice3"></span></button>
            </div>

            <hr style="margin-top: 50px">
            <footer>
                <p id="progress">Question x of y</p>
            </footer>
        </div>
    </div>


<script src="question.js"></script>

</body>
</html>
qTips
  • 13
  • 1
  • 7
  • 3
    You can't `addEventListener()` on a string. Strings do not have events. – Taplar Aug 12 '20 at 18:30
  • Please read https://stackoverflow.com/help/how-to-ask – Andy Ray Aug 12 '20 at 18:31
  • Could you please be more specific about what and where ? – mttetc Aug 12 '20 at 18:34
  • @Hisato yes it's on the function called "showScores", in there am using the "addEventListener". – qTips Aug 12 '20 at 18:37
  • @sgibson19 "Also if you see any other issues with my code please let me know" ... this part would be appropriate on codereview.stackexchange.com but only after you get your code working. Stackoverflow is for specific questions that (can) have specific answers, so broad requests like this are generally off-topic. There is a [great rundown](https://meta.stackexchange.com/a/129632/138482) of SE sites and their topics on [meta] – Stephen P Aug 12 '20 at 19:09

1 Answers1

0

You should just use event delegation, it's very efficient. Here a very generic piece of code that will do what you want. It will work with your generated button, you just have to change classes I target in the event() function.

const event = () => {
    document.querySelector('.your-quizz').addEventListener('click', event => {
       if (event.target.closest('.your-button')) {
          restart();
       }
    });
};

const restart = () => {
    console.log('restart here')
};

event();
<div class="your-quizz">
   <button class="your-button">restart</button>
</div>
mttetc
  • 711
  • 5
  • 12