Lesson 8

Cycling through questions

Listening for user input and responding accordingly

Continuing with what we've got, we can now create a function that will run when our user clicks on an answer. Like before, we set up a function, but this time we use jQuery to detect when a user clicks on a span:

This can sit below our existing code in script-1.js

When a user clicks on an answer, the first thing we want to do is detect if the user is correct or not. We can use some logic to do this. It will be an if statement that will check if the answer has the class "correct". If it does we'll add 1 to the user's score using JavaScript's ++ command.

Once this is done we can also update the score to show the user how many questions they've got right so far.

We select the span with a class of "score", and then use jQuery's "html" function to pass the span the current value of our score variable.

Now that we've checked if our user got the question right or not, we need to show them the next question. We can do this by adding 1 to our question number variable, and then running the showQuestion function that we've already created:

The last thing we need to do in our showQuestion function is check that the user hasn't finished the quiz. If they have, we want to show them the final screen. We can use jQuery to detect if the next question exists. If it does, we'll show that question. If it doesn't, we can assume that the user is at the end of the quiz and show them the final screen.

Go to the next lesson



the web page

New Window
Next Lesson