Develop a quiz app for html. 30 quesions within 20 mins Show the timer and if the timer completes it will auto submit, if they refresh the page it will also auto submit. It will also show their result, percentage, and the ones they got correct and incorrect at the end of the quiz. And they will not be able to restart the quiz till after 2 hours. Use pure html, css and vanila javascript. Do not use any framework
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete quiz app that meets all your requirements using pure HTML, CSS, and vanilla JavaScript:
html
<!DOCTYPE html>
<html>
<head>
<title>Timed Quiz App</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, 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 10px rgba(0,0,0,0.1);
}
.hidden { display: none; }
h1 {
color: #1877f2;
text-align: center;
margin-bottom: 30px;
}
#timer {
text-align: center;
margin: 20px 0;
font-size: 1.5em;
color: #333;
}
#progress {
text-align: center;
margin: 10px 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 (20 Minutes)</h1>
<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">Time Left: 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 timer;
let startTime = 0;
let timeRemaining = 20 * 60; // 20 minutes in seconds
// 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 },
{ question: "What is the chemical symbol for gold?", answers: ["Ag", "Au", "Fe", "Cu"], correct: 1 },
{ question: "How many sides does a hexagon have?", answers: ["5", "6", "7", "8"], correct: 1 },
{ question: "Who wrote 'To be or not to be'?", answers: ["Shakespeare", "Dickens", "Tolstoy", "Hemingway"], correct: 0 },
{ question: "What gas do plants absorb?", answers: ["Oxygen", "Nitrogen", "Carbon Dioxide", "Hydrogen"], correct: 2 },
{ question: "Which planet is known as the Red Planet?", answers: ["Mars", "Venus", "Jupiter", "Saturn"], correct: 0 },
{ question: "What is the capital of Japan?", answers: ["Seoul", "Tokyo", "Beijing", "Bangkok"], correct: 1 },
{ question: "How many colors are in a rainbow?", answers: ["5", "6", "7", "8"], correct: 2 },
{ question: "Which is not a prime number?", answers: ["2", "3", "4", "5"], correct: 2 },
{ question: "Who discovered penicillin?", answers: ["Einstein", "Fleming", "Newton", "Curie"], correct: 1 },
{ question: "What is H2O?", answers: ["Water", "Fire", "Air", "Earth"], correct: 0 },
{ question: "Which planet is closest to the sun?", answers: ["Venus", "Earth", "Mercury", "Mars"], correct: 2 },
{ question: "How many bones are in the human body?", answers: ["206", "207", "208", "209"], correct: 0 },
{ question: "Which is a Fibonacci number?", answers: ["4", "5", "6", "7"], correct: 1 },
{ question: "What is the tallest mammal?", answers: ["Elephant", "Giraffe", "Blue Whale", "Kangaroo"], correct: 1 },
{ question: "Which is a leap year?", answers: ["1900", "2000", "2100", "2200"], correct: 1 },
{ question: "What is the chemical symbol for iron?", answers: ["Ir", "Fe", "In", "Io"], correct: 1 },
{ question: "How many hours in a day?", answers: ["22", "23", "24", "25"], correct: 2 },
{ question: "What is the square root of 64?", answers: ["6", "7", "8", "9"], correct: 2 },
{ question: "Which bird can fly backwards?", answers: ["Sparrow", "Hummingbird", "Eagle", "Ostrich"], correct: 1 },
{ question: "What is the largest ocean?", answers: ["Atlantic", "Indian", "Arctic", "Pacific"], correct: 3 }
];
// Check if quiz has already been completed
document.addEventListener('DOMContentLoaded', checkCooldown);
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;
}
}
// Start quiz
startBtn.addEventListener('click', () => {
// Check if user has already taken the quiz recently
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) {
alert("You can retake the quiz after 2 hours!");
return;
}
}
// Initialize quiz
currentQuestionIndex = 0;
userAnswers = new Array(questions.length).fill(null);
score = 0;
// Check if there's existing quiz data
const savedAnswers = localStorage.getItem('userAnswers');
if (savedAnswers) {
userAnswers = JSON.parse(savedAnswers);
}
const savedStartTime = localStorage.getItem('quizStartTime');
if (savedStartTime) {
startTime = parseInt(savedStartTime);
const now = new Date().getTime();
const elapsed = Math.floor((now - startTime) / 1000);
timeRemaining = Math.max(0, 20 * 60 - elapsed);
} else {
startTime = new Date().getTime();
localStorage.setItem('quizStartTime', startTime);
}
startScreen.classList.add('hidden');
resultsElement.classList.add('hidden');
quizElement.classList.remove('hidden');
displayQuestion();
startTimer();
});
// Display current question
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');
}
}
// Handle answer selection
function selectAnswer(selectedIndex) {
userAnswers[currentQuestionIndex] = selectedIndex;
localStorage.setItem('userAnswers', JSON.stringify(userAnswers));
const options = optionsElement.querySelectorAll('.option-btn');
options.forEach(option => {
option.classList.remove('selected');
if (parseInt(option.dataset.index) === selectedIndex) {
option.classList.add('selected');
}
});
}
// Navigation buttons
prevBtn.addEventListener('click', () => {
if (currentQuestionIndex > 0) {
currentQuestionIndex--;
displayQuestion();
}
});
nextBtn.addEventListener('click', () => {
if (currentQuestionIndex < questions.length - 1) {
currentQuestionIndex++;
displayQuestion();
}
});
submitBtn.addEventListener('click', () => {
if (confirm("Are you sure you want to submit?")) {
calculateResults();
}
});
// Timer functions
function startTimer() {
// Clear any existing timer
clearInterval(timer);
// Update timer every second
timer = setInterval(() => {
const now = new Date().getTime();
const elapsed = Math.floor((now - startTime) / 1000);
timeRemaining = Math.max(0, 20 * 60 - elapsed);
// Update display
const minutes = Math.floor(timeRemaining / 60);
const seconds = timeRemaining % 60;
timerElement.textContent = `Time Left: ${minutes}:${seconds.toString().padStart(2, '0')}`;
// Auto-submit when time runs out
if (timeRemaining <= 0) {
clearInterval(timer);
calculateResults();
}
}, 1000);
}
// Calculate and display results
function calculateResults() {
clearInterval(timer);
// Calculate score
score = 0;
userAnswers.forEach((answer, index) => {
if (answer === questions[index].correct) {
score++;
}
});
// Save completion time
localStorage.setItem('quizCompletedTime', new Date().getTime());
// Clear quiz data
localStorage.removeItem('quizStartTime');
localStorage.removeItem('userAnswers');
// Display results
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)}%`;
// Display detailed results
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: ${userAnswer !== null ? 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);
});
// Check cooldown for restart button
checkCooldown();
}
// Auto-submit on page refresh or close
window.addEventListener('beforeunload', () => {
if (!localStorage.getItem('quizCompletedTime') && startTime > 0) {
calculateResults();
return false;
}
});
// Handle page load
window.addEventListener('load', () => {
// Check if there's an ongoing quiz
const savedStartTime = localStorage.getItem('quizStartTime');
if (savedStartTime) {
const now = new Date().getTime();
const elapsed = Math.floor((now - parseInt(savedStartTime)) / 1000);
// If time has expired, auto-submit
if (elapsed >= 20 * 60) {
calculateResults();
} else {
// Otherwise, continue the quiz
startBtn.click();
}
}
});
</script>
</body>
</html>
This quiz app includes all the features you requested:
30 Questions: The example includes 30 questions in the questions array. Replace them with your actual questions.
20-Minute Timer:
Countdown timer that starts at 20:00
Automatically submits quiz when time runs out
Persists across page reloads using localStorage
Auto-Submit Functionality:
Auto-submits when timer reaches 0
Auto-submits if user tries to refresh/close the page
Saves progress in localStorage
Results Display:
Shows score and percentage
Lists each question with correct/incorrect indication
Highlights correct and incorrect answers in different colors
2-Hour Cooldown:
Prevents retaking quiz for 2 hours after submission
Uses localStorage to track completion time
Shows countdown of remaining cooldown time
Navigation Features:
Previous/Next buttons to navigate questions
Submit button on final question
Visual feedback for selected answers
Data Persistence:
Saves user answers and timer state
Restores quiz state on page reload
Clears data after submission
The app uses localStorage to persist quiz state across page reloads and tracks quiz completion to enforce the 2-hour cooldown. The timer continues counting down even if the page is refreshed, and the quiz auto-submits when time runs out or if the user tries to leave the page.
To use this quiz:
Replace the example questions in the questions array with your actual 30 questions
Each question should have:
question: The question text
answers: Array of answer options
correct: Index of the correct answer (0-based)
The app will handle the rest, including time tracking, progress saving, and result calculation.