How to create a simple quiz using HTML CSS and JavaScript
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Quiz Generator</title><link rel="stylesheet" href="styles.css"></head><body><div class="quiz-container"><h1>Quiz Time!</h1><div id="quiz"></div><button id="submit">Submit Answers</button><div id="results"></div></div><script src="quiz.js"></script></body></html>
CSS
/* Add your CSS styles here */
.quiz-container {
max-width: 600px;
margin: 0 auto;
text-align: center;
}
/* Add more styles as needed */
JAVASCRIPT
// Define your quiz questions and answers
const quizData = [
{
question: "What language is used for web page structure?",
answers: {
a: "HTML",
b: "CSS",
c: "JavaScript"
},
correctAnswer: "a"
},
{
question: "Which language adds style to a web page?",
answers: {
a: "JavaScript",
b: "HTML",
c: "CSS"
},
correctAnswer: "c"
},
{
question: "Which language adds interactivity to a web page?",
answers: {
a: "CSS",
b: "JavaScript",
c: "HTML"
},
correctAnswer: "b"
}
];
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
// Function to generate quiz
function generateQuiz() {
const output = [];
quizData.forEach((questionData, questionIndex) => {
const answers = [];
for (const letter in questionData.answers) {
answers.push(
`<label>
<input type="radio" name="question${questionIndex}" value="${letter}">
${letter}: ${questionData.answers[letter]}
</label>`
);
}
output.push(
`<div class="question">${questionData.question}</div>
<div class="answers">${answers.join('')}</div>`
);
});
quizContainer.innerHTML = output.join('');
}
// Function to show results
function showResults() {
const answerContainers = quizContainer.querySelectorAll('.answers');
let numCorrect = 0;
quizData.forEach((questionData, questionIndex) => {
const answerContainer = answerContainers[questionIndex];
const selector = `input[name=question${questionIndex}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
if (userAnswer === questionData.correctAnswer) {
numCorrect++;
answerContainers[questionIndex].style.color = 'green';
} else {
answerContainers[questionIndex].style.color = 'red';
}
});
resultsContainer.innerHTML = `${numCorrect} out of ${quizData.length} correct`;
}
OUTPUT
// Generate quiz on page load
generateQuiz();
// Event listener for submit button
submitButton.addEventListener('click', showResults);
Comments :
Post a Comment