Here's a complete quiz app with timer, auto-submit, and cooldown features using pure HTML, CSS, and vanilla JavaScript:
html Copy code
<!DOCTYPE html>
<html>
<head>
<title>Quiz App with Timer</title>
<style>
body {
font-family: 'Segoe UI', sans-serif;
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #f0f2f5;
}
.quiz-container {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 15px rgba(0,0,0,0.1);
}
.hidden { display: none; }
h1 {
color: #1877f2;
text-align: center;
margin-bottom: 30px;
}
#timer {
text-align: center;
font-size: 1.5em;
margin: 20px 0;
color: #e41e3f;
font-weight: bold;
}
#progress {
text-align: center;
margin: 20px 0;
color: #65676b;
}
#question {
font-size: 1.2em;
margin: 25px 0;
color: #333;
}
.option-btn {
display: block;
width: 100%;
padding: 12px;
margin: 8px 0;
background: #f0f2f5;
border: none;
border-radius: 5px;
cursor: pointer;
text-align: left;
transition: all 0.3s ease;
}
.option-btn:hover {
background: #e4e6eb;
}
.option-btn.selected {
background: #1877f2;
color: white;
}
button {
background: #1877f2;
color: white;
border: none;
padding: 12px 25px;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
margin: 10px 5px;
transition: background 0.3s ease;
}
button:hover {
background: #166fe5;
}
button:disabled {
background: #d4d4d4;
cursor: not-allowed;
}
#results {
text-align: center;
}
#score, #percentage {
font-size: 1.2em;
margin: 20px 0;
color: #333;
}
#answers-review {
margin-top: 30px;
text-align: left;
}
.correct {
color: #42b72a;
}
.incorrect {
color: #e41e3f;
}
#cooldown-msg {
color: #e41e3f;
text-align: center;
margin-top: 15px;
}
</style>
</head>
<body>
<div class="quiz-container">
<div id="start-screen">
<h1>30-Question Quiz</h1>
<p>You have 20 minutes to complete the quiz</p>
<button id="start-btn">Start Quiz</button>
<p id="cooldown-msg" class="hidden">You can retake the quiz in <span id="cooldown-time"></span></p>
</div>
<div id="quiz" class="hidden">
<div id="timer">20:00</div>
<div id="progress"></div>
<div id="question"></div>
<div id="options"></div>
<div style="text-align: center;">
<button id="prev-btn">Previous</button>
<button id="next-btn">Next</button>
<button id="submit-btn" class="hidden">Submit</button>
</div>
</div>
<div id="results" class="hidden">
<h1>Quiz Results</h1>
<p id="score"></p>
<p id="percentage"></p>
<div id="answers-review"></div>
<button id="restart-btn">Restart Quiz</button>
</div>
</div>
<script>
// DOM Elements
const startScreen = document.getElementById('start-screen');
const quizElement = document.getElementById('quiz');
const resultsElement = document.getElementById('results');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const submitBtn = document.getElementById('submit-btn');
const timerElement = document.getElementById('timer');
const progressElement = document.getElementById('progress');
const questionElement = document.getElementById('question');
const optionsElement = document.getElementById('options');
const scoreElement = document.getElementById('score');
const percentageElement = document.getElementById('percentage');
const answersReviewElement = document.getElementById('answers-review');
const cooldownMsg = document.getElementById('cooldown-msg');
const cooldownTime = document.getElementById('cooldown-time');
// Quiz State
let currentQuestionIndex = 0;
let userAnswers = [];
let score = 0;
let timeLeft = 20 * 60; // 20 minutes in seconds
let timerInterval;
let quizStartTime;
// Questions Array (30 questions)
const questions = [
// Example questions (replace with your 30 questions)
{ question: "What is 2+2?", answers: ["3", "4", "5", "6"], correct: 1 },
{ question: "Capital of France?", answers: ["London", "Paris", "Berlin", "Madrid"], correct: 1 },
{ question: "Largest planet?", answers: ["Earth", "Mars", "Jupiter", "Saturn"], correct: 2 },
{ question: "Boiling point of water (°C)?", answers: ["90", "100", "110", "120"], correct: 1 },
{ question: "Fastest land animal?", answers: ["Cheetah", "Lion", "Leopard", "Tiger"], correct: 0 },
// Add 25 more questions following the same pattern...
// For brevity, I'm adding 5 more example questions
{ question: "How many continents are there?", answers: ["5", "6", "7", "8"], correct: 2 },
{ question: "What is the hardest part of the human body?", answers: ["Ribs", "Skull", "Teeth", "Femur"], correct: 2 },
{ question: "Which element has the chemical symbol 'Na'?", answers: ["Nitrogen", "Sodium", "Nickel", "Neon"], correct: 1 },
{ question: "What is the smallest country in the world?", answers: ["Monaco", "Vatican", "San Marino", "Liechtenstein"], correct: 1 },
{ question: "Who painted the Mona Lisa?", answers: ["Van Gogh", "Picasso", "Da Vinci", "Michelangelo"], correct: 2 }
];
// Initialize userAnswers array
userAnswers = new Array(questions.length).fill(null);
// Check cooldown and resume state on page load
document.addEventListener('DOMContentLoaded', () => {
checkCooldown();
checkResumeState();
});
function checkCooldown() {
const completionTime = localStorage.getItem('quizCompletedTime');
if (completionTime) {
const now = new Date().getTime();
const diff = now - parseInt(completionTime);
const twoHours = 2 * 60 * 60 * 1000;
if (diff < twoHours) {
const remaining = Math.ceil((twoHours - diff) / (60 * 1000));
cooldownMsg.classList.remove('hidden');
cooldownTime.textContent = `${remaining} minutes`;
startBtn.disabled = true;
} else {
localStorage.removeItem('quizCompletedTime');
startBtn.disabled = false;
}
} else {
startBtn.disabled = false;
}
}
function checkResumeState() {
const savedTime = localStorage.getItem('quizTimeRemaining');
const savedStartTime = localStorage.getItem('quizStartTime');
if (savedTime && savedStartTime) {
const now = new Date().getTime();
const elapsed = Math.floor((now - parseInt(savedStartTime)) / 1000);
timeLeft = parseInt(savedTime) - elapsed;
if (timeLeft <= 0) {
calculateResults();
} else {
startQuiz();
startTimer();
}
}
}
startBtn.addEventListener('click', startQuiz);
restartBtn.addEventListener('click', startQuiz);
function startQuiz() {
currentQuestionIndex = 0;
userAnswers = new Array(questions.length).fill(null);
timeLeft = 20 * 60;
quizStartTime = new Date().getTime();
// Save start time
localStorage.setItem('quizStartTime', quizStartTime);
localStorage.setItem('quizTimeRemaining', timeLeft);
startScreen.classList.add('hidden');
resultsElement.classList.add('hidden');
quizElement.classList.remove('hidden');
displayQuestion();
startTimer();
// Handle page refresh
window.addEventListener('beforeunload', () => {
localStorage.setItem('quizStartTime', quizStartTime);
localStorage.setItem('quizTimeRemaining', timeLeft);
});
}
function startTimer() {
clearInterval(timerInterval);
timerInterval = setInterval(() => {
timeLeft--;
updateTimerDisplay();
// Save remaining time every second
localStorage.setItem('quizTimeRemaining', timeLeft);
if (timeLeft <= 0) {
clearInterval(timerInterval);
calculateResults();
}
}, 1000);
}
function updateTimerDisplay() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
// Add warning when time is low
if (timeLeft <= 60) {
timerElement.style.color = '#ff0000';
}
}
function displayQuestion() {
const currentQuestion = questions[currentQuestionIndex];
progressElement.textContent = `Question ${currentQuestionIndex + 1}/${questions.length}`;
questionElement.textContent = currentQuestion.question;
optionsElement.innerHTML = '';
currentQuestion.answers.forEach((answer, index) => {
const option = document.createElement('button');
option.textContent = answer;
option.className = 'option-btn';
option.dataset.index = index;
if (userAnswers[currentQuestionIndex] == index) {
option.classList.add('selected');
}
option.addEventListener('click', () => selectAnswer(index));
optionsElement.appendChild(option);
});
prevBtn.disabled = currentQuestionIndex === 0;
nextBtn.classList.remove('hidden');
submitBtn.classList.add('hidden');
if (currentQuestionIndex === questions.length - 1) {
nextBtn.classList.add('hidden');
submitBtn.classList.remove('hidden');
}
}
function selectAnswer(selectedIndex) {
userAnswers[currentQuestionIndex] = selectedIndex;
const options = optionsElement.querySelectorAll('.option-btn');
options.forEach(option => {
option.classList.remove('selected');
if (parseInt(option.dataset.index) === selectedIndex) {
option.classList.add('selected');
}
});
}
prevBtn.addEventListener('click', () => {
if (currentQuestionIndex > 0) {
currentQuestionIndex--;
displayQuestion();
}
});
nextBtn.addEventListener('click', () => {
if (currentQuestionIndex < questions.length - 1) {
currentQuestionIndex++;
displayQuestion();
}
});
submitBtn.addEventListener('click', calculateResults);
function calculateResults() {
clearInterval(timerInterval);
localStorage.removeItem('quizStartTime');
localStorage.removeItem('quizTimeRemaining');
score = 0;
userAnswers.forEach((answer, index) => {
if (answer === questions[index].correct) {
score++;
}
});
quizElement.classList.add('hidden');
resultsElement.classList.remove('hidden');
scoreElement.textContent = `Correct Answers: ${score}/${questions.length}`;
const percentage = (score / questions.length) * 100;
percentageElement.textContent = `Percentage: ${percentage.toFixed(2)}%`;
answersReviewElement.innerHTML = '';
questions.forEach((question, index) => {
const userAnswer = userAnswers[index];
const isCorrect = userAnswer === question.correct;
const div = document.createElement('div');
div.innerHTML = `
<p><strong>Question ${index + 1}:</strong> ${question.question}</p>
<p>Your Answer: ${question.answers[userAnswer] || 'Unanswered'}</p>
<p>Correct Answer: ${question.answers[question.correct]}</p>
<p class="${isCorrect ? 'correct' : 'incorrect'}">${isCorrect ? '✓ Correct' : '✗ Incorrect'}</p>
`;
answersReviewElement.appendChild(div);
});
// Save completion time
localStorage.setItem('quizCompletedTime', new Date().getTime());
// Check cooldown for restart button
const now = new Date().getTime();
const completionTime = parseInt(localStorage.getItem('quizCompletedTime'));
const diff = now - completionTime;
const twoHours = 2 * 60 * 60 * 1000;
restartBtn.disabled = diff < twoHours;
}
// Initial checks
checkCooldown();
</script>
</body>
</html>
The 2-hour cooldown prevents multiple attempts using localStorage.