I need help using "addEventListener" to my project

Hello fellow programmers, I need help using addEventListener to my project. I have made a little quiz and at the end of the quiz am asking the user whether they would like to re do their quiz again. I have tried using stackoverflow but instead of helping me, I instead get told by other users to write a better question or it has too much code in it, etc. Stack Overflow is great help but at times instead of helping you, they criticize you instead. If anyone would like to help me, I gladly share my code. Thanks

<!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>
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;
}

// this is the functio to restart the quiz
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); //this is where I add my "addEventListener"
    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();

What is the question, exactly (not asked in a mean voice)?

No problem, I have made a little quiz using JS, HTML, and CSS. At the end of the quiz I would like to give the user the option to redo the quiz, if they liked to. On stack overflow, they have told me to either use “addEventListener” or to use “event delegation”.

Well, they might be right in a general sense, but I’m guessing that you are looking for more specific recommendations, right? I think you can just paste your code here, surrounded in front and back with three backticks, and people can take a look at it.

Also, you might consider exactly how you want that choice to be presented to the user:

  1. a window that pops up, asking the question?
  2. something displayed in the html?
  3. a button they can press to play again?

OK, I have added my code

Okay, so after they are finished with the quiz, you call showScores(), right? How about put something in there that gives the user the option to play again after the scores have been displayed?

Yes correct, but that is why I have added the shuffle_questions and restart functions, I guess my problem is displaying the message whether would like to re do the quiz. Am I using the “addEventListener” correctly?

I don’t think so… I think just this (I removed the += operator):

gameOverHTML.addEventListener("click", restart); //this is where I add my "addEventListener"

would be enough to cause a click on the gameOverHTML element.

But I think you need to first grab something in the DOM in order to be able to click it. The easiest way to do that is add an id to whatever you want to click. So say you wanted them to click on an h2> it could be like

<h2 id="clickable">Click here to play again</h2>

then in the JS,

const newQuiz = document.getElementById("clickable"); //this gets the element 
newQuiz.addEventListener("click", reset); //this captures the click and calls the reset() function.
1 Like

Yea am completely lost @CactusWren2020. I have tried doing what you have recommended me but it’s still not working.

I’m sorry about that, I thought it would work, but wouldn’t really know unless I took it all over here and tested and debugged it.

My suggestion would be to try to test things part by part, sometimes even line by line. Like–I’m not sure if you’ve used event listeners before, so maybe just make a little one that consoles out something to make sure it works? Then if it’s actually doing anything, then you add the function into the event listener. I like to do things like that, otherwise I can’t tell what’s the problem–the function, the event listener, or something else.

So I were going to do that with event listeners, maybe I’d write something like:

let button = document.getElementById("btn"); //this refers to a button I put, say <button id="btn">Test</button>

function  test() {
console.log("yay, this works");
}

button.addEventListener("click", test);  // now the button is "listening" for a click.

Now, if this works in your console, you can just copy the same idea over to make your game functions do things.

Hope this helps a bit.

Hey there,

if you provide us:

  • a codepen with your current code
  • a clear description what you want to achieve
  • a clear description what you’ve tried so far and why it didn’t work,

it’ll be much easier to help you.

https://codepen.io/sgibson19
That is my codepen, it’s the quiz project.

What I want to achieve is to give the user the option at the end of the quiz to re do the quiz and shuffle the questions also.

In there I have added the “restart” and “shuffle_questions” functions but I have remove the “addEventListener” and everything that cactuswaren has recommended me. Also the “shuffle_questions” function isn’t working. Thanks any help would be amazing.

Alright, thanks!

So if you divide this big goal into tiny steps, how would they look like?
What is a first viable step you can achieve?

sorry for the late reply, I have solved the issue!!! Now am working on the backend part using node.js. Am using express and passport login to create a user login.

1 Like