jQuery Mobile: Interactive Quiz with Score Tracking using JavaScript

jQuery Mobile makes it easy to create an interactive quiz and JavaScript can keep track of the user’s score by creating a variable and storing the value. In the sample code below you will note the variable totalScore is used within the myScore() function. The score out of 10 is generated, displayed and reset to zero using the following JavaScript:

<script>
 // add a point to the score
 var totalScore = 0;
 $("#score").hide();
 function myScore() {
 totalScore++;
 }
 // display the score
 function display() {
 $("#score").show();
 $("#score").html("Your Score: " + totalScore + "/10");
 }
 // reset the score to zero
 function refresh() {
 totalScore = 0;
 $("#score").hide();
 }
</script>

The HTML to call each of the functions is simply onclick=”myFunction()” and is placed within the anchor tag of the button clicked. In summary, you render each of the possible answers as a button and have the onclick event within its anchor tag. For example, the following code is used within the quiz to call the myScore() function which will add a point to the score:

<a href="#q2a" onclick="myScore()" data-role="button" data-rel="popup" data-position-to="window" data-transition="pop">true</a>

The display() function is called on the last page of the quiz where the user can find out their final score out of 10. Finally, the refresh() function is used to reset the score to zero if the user chooses to “Start Over” and try the quiz again.

In Summary: The jQuery Mobile Quiz Demo

I started by introducing jQuery Mobile and discussed how to get your development environment set up by linking to the jQuery library and jQuery Mobile framework’s files. Next, I went into the details of how to create your first page by discovering the page architecture of jQuery Mobile.

I wrote a post on creating a multiple choice quiz using radio buttons and providing feedback by using a “Check Answer” button and some JavaScript. Next, in the post on creating popup widgets to provide feedback you learned how to make sure the user interacts with the popup to close it.

And finally within this post you learn how to integrate keeping track of the score by using JavaScript.

To check out the entire jQuery Mobile quiz I have uploaded a demo available here. The code is available for you to see how everything fits together as a web app.

 

Comments (0)

Leave a Comment