Calling function second time in JavaScript Posted May 25, 2019 I am building a quiz with an array which has questions and options. First time the function is called successfully but when restarting the quiz, the function is not invoked. // Showing questions and options var x = " "; var i = 0; function showQuestions() { document.getElementById('holder').innerHTML = x; for (j = 0; j < words.options.length; j++) { if (i < words.length) { $('#holder').append("<div id=" + words.options[j] + " class='alternatives'>" + words.options[j] + "</div>"); } } if (i < words.length) { $('#holder').append('<div id="quest">' + words.question + '</div>'); i++; } } showQuestions(); // Calling function on click of alternatives $('#holder').on('click', '.alternatives', function() { showQuestions(); }); // Checking answers score = 0; k = 0; $(document).on('click', '.alternatives', function() { let guess = this.id; if (k < words.length) { var correct = words[k].answer; k++; } if (guess === correct) { score++; } if (score <= words.length) { z = score; document.getElementById('summary').innerHTML = z; } if (k >= words.length) { $('#holder').fadeOut(); $('#restart').fadeIn(); } }); // Restarting Quiz // show Questions function is not working $(document).on('click', '#restart', function() { $(this).fadeOut(); $('#holder').fadeIn(); showQuestions(); });
Calling function second time
in JavaScript
Posted
I am building a quiz with an array which has questions and options. First time the function is called successfully but when restarting the quiz, the function is not invoked.
// Showing questions and options
var x = " ";
var i = 0;
function showQuestions() {
document.getElementById('holder').innerHTML = x;
for (j = 0; j < words.options.length; j++) {
if (i < words.length) {
$('#holder').append("<div id=" + words.options[j] + " class='alternatives'>" + words.options[j] + "</div>");
}
}
if (i < words.length) {
$('#holder').append('<div id="quest">' + words.question + '</div>');
i++;
}
}
showQuestions();
// Calling function on click of alternatives
$('#holder').on('click', '.alternatives', function() {
showQuestions();
});
// Checking answers
score = 0;
k = 0;
$(document).on('click', '.alternatives', function() {
let guess = this.id;
if (k < words.length) {
var correct = words[k].answer;
k++;
}
if (guess === correct) {
score++;
}
if (score <= words.length) {
z = score;
document.getElementById('summary').innerHTML = z;
}
if (k >= words.length) {
$('#holder').fadeOut();
$('#restart').fadeIn();
}
});
// Restarting Quiz
// show Questions function is not working
$(document).on('click', '#restart', function() {
$(this).fadeOut();
$('#holder').fadeIn();
showQuestions();
});