Andrew Nguyen Andrew Nguyen - 4 years ago 117
Javascript Question

Resetting score to 0 after quiz completed

Problem



I have a
resetQuiz()
quiz button at the bottom of the page, which is supposed to set the score back to 0, but if the person has gotten 25 correct answers, clicks
.button__reset
and then does the quiz again, it goes to 26 instead of 0.

Live link: https://s3.amazonaws.com/bsunproduction/yearinreview/index.html

scripts.js



/*-------------------------------------
QUIZ
--------------------------------------*/

// Keep track of score
function showScoreBox() {
var scrollDepth = $(window).scrollTop();
var divPosition = $(".quiz__header").offset().top - 45;
var windowWidth = $(window).width();
// console.log(windowWidth);

if (scrollDepth > divPosition && (windowWidth > 768)) {
$(".quiz__score").show();
$(".quiz__score--mobile").hide();
} else {
$(".quiz__score").hide();
$(".quiz__score--mobile").show();
}
} showScoreBox();

$(window).on("scroll", function(){
showScoreBox();
});

$(window).on("resize", function(){
showScoreBox();
});

var score = 0;

$(document).on("click", ".quiz__response", function(){
$(this).siblings().addBack().addClass("is--unclickable");
$(this).siblings().show("quiz__info"); // Show extra info
console.log("Clicked");

if ($(this).hasClass("answer--true")) {
$(this).addClass("is--true");
$(this).find("i").show();
$(this).siblings().find("i").show();

// Update score
score++
console.log(score);
$(".quiz__correct").html(score);
$(".quiz__correct--mobile").html(score);
rainConfetti();
} else {
// $(this).addClass("is--true");
// $(this).siblings().addClass("is--false");
// $("quiz__info").removeClass("is--false");
$(this).addClass("is--false");
$(this).find("i").show();
$(this).siblings().find("i").show();
}
});

/*-------------------------------------
RESET
--------------------------------------*/

function resetQuiz() {
var score = 0;
$(".quiz__response").removeClass("is--true is--false");
$(".quiz__response").removeClass("is--unclickable");
$(".fa-check").hide();
$(".fa-times").hide();
$(".quiz__correct").html(score);
$(".quiz__correct--mobile").html(score);
}

$(".button__reset").on("click", function(){
var score = 0;
$("canvas").hide();
resetQuiz();
});

Answer Source

You are creating a new variable & assigning it the value 0 instead of the global one.

Instead of var score = 0; use score = 0; inside resetQuiz

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download