Quiz with Timer and Progress
Quiz with Timer and Progress
let currentQuestion = 0;
let selectedAnswers = [];
let hasSubmitted = false;
let correct = 0; // Variable to track the number of correct answers
const questions = [
{
question: "What is the capital of France?",
options: ["Paris", "London", "Rome", "Berlin"],
correctAnswer: "Paris"
},
{
question: "Which planet is known as the Red Planet?",
options: ["Earth", "Mars", "Jupiter", "Saturn"],
correctAnswer: "Mars"
},
// Add more questions as needed
];
function displayQuestion() {
if (currentQuestion < questions.length) {
const questionObj = questions[currentQuestion];
document.getElementById('question').textContent = questionObj.question;
const optionsContainer = document.getElementById('options');
optionsContainer.innerHTML = ''; // Clear previous options
questionObj.options.forEach(option => {
const optionElem = document.createElement('button');
optionElem.textContent = option;
optionElem.onclick = () => selectAnswer(option);
optionsContainer.appendChild(optionElem);
});
} else {
showResult();
}
}
function selectAnswer(option) {
if (hasSubmitted) return; // Prevent selection after submission
selectedAnswers[currentQuestion] = option;
currentQuestion++;
displayQuestion();
}
function showResult() {
correct = 0;
// Check answers
questions.forEach((question, index) => {
if (selectedAnswers[index] === question.correctAnswer) {
correct++;
}
});
const obtainedMarks = correct;
const maxMarks = questions.length;
// Save result in local storage
saveResult(obtainedMarks, maxMarks);
document.getElementById('result-summary').innerHTML = `You got ${correct} out of ${maxMarks} correct.`;
document.getElementById('result-section').style.display = 'block';
document.getElementById('quiz-section').style.display = 'none';
document.getElementById('statistics-btn').style.display = 'block'; // Show statistics button
hasSubmitted = true; // Set flag to prevent resubmission
}
// Save the result and update local storage
function saveResult(obtainedMarks, maxMarks) {
// Fetch existing statistics from local storage
let stats = JSON.parse(localStorage.getItem('quizStats')) || {
totalAttempts: 0,
totalObtainedMarks: 0,
totalMarks: 0
};
// Update statistics
stats.totalAttempts++;
stats.totalObtainedMarks += obtainedMarks;
stats.totalMarks += maxMarks;
// Save updated stats back to local storage
localStorage.setItem('quizStats', JSON.stringify(stats));
// Update statistics UI dynamically
updateStatistics();
}
// Update statistics display dynamically
function updateStatistics() {
let stats = JSON.parse(localStorage.getItem('quizStats')) || {
totalAttempts: 0,
totalObtainedMarks: 0,
totalMarks: 0
};
const averagePercentage = stats.totalMarks > 0 ? (stats.totalObtainedMarks / stats.totalMarks) * 100 : 0;
document.getElementById('total-attempts').textContent = stats.totalAttempts;
document.getElementById('obtained-marks').textContent = stats.totalObtainedMarks;
document.getElementById('total-marks').textContent = stats.totalMarks;
document.getElementById('average-percentage').textContent = averagePercentage.toFixed(2);
// Update progress bar
const progressBar = document.getElementById('progress-bar');
progressBar.style.width = `${averagePercentage}%`;
}
// Show statistics section
function showStatistics() {
updateStatistics(); // Ensure stats are up to date before showing
const statisticsSection = document.getElementById('statistics-section');
statisticsSection.style.display = 'block';
}
// Reset the quiz and clear the result
function resetQuiz() {
currentQuestion = 0;
selectedAnswers = [];
hasSubmitted = false; // Reset submission flag
document.getElementById('result-summary').innerHTML = '';
document.getElementById('result-section').style.display = 'none';
document.getElementById('quiz-builder').style.display = 'block';
document.getElementById('quiz-section').style.display = 'none';
document.getElementById('statistics-btn').style.display = 'none'; // Hide statistics button after reset
}
// Call this function when the page loads to display the first question
window.onload = displayQuestion;