Basic Quiz System JavaScript, HTML, CSS

👤 Sharing: AI
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Quiz</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
        }

        .quiz-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 600px;
            padding: 20px;
            text-align: center;
        }

        h1 {
            color: #333;
        }

        .question {
            font-size: 1.2em;
            margin-bottom: 20px;
        }

        .options {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            margin-bottom: 20px;
        }

        .options button {
            padding: 10px 20px;
            margin: 5px 0;
            border: none;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            text-align: left; /* Align text left within the button */
        }

        .options button:hover {
            background-color: #0056b3;
        }

        #result {
            font-weight: bold;
            margin-top: 20px;
            color: #28a745; /* Green for success */
        }

        #next-button {
            padding: 10px 20px;
            border: none;
            background-color: #28a745;
            color: white;
            border-radius: 5px;
            cursor: pointer;
            display: none;  /* Initially hide the button */
        }

        #next-button:hover {
            background-color: #1e7e34;
        }
    </style>
</head>
<body>

    <div class="quiz-container">
        <h1>Simple Quiz</h1>
        <div id="question" class="question"></div>
        <div id="options" class="options"></div>
        <div id="result"></div>
        <button id="next-button">Next Question</button>
    </div>

    <script>
        const quizData = [
            {
                question: "What is the capital of France?",
                options: ["Berlin", "Madrid", "Paris", "Rome"],
                correctAnswer: "Paris"
            },
            {
                question: "What is the largest planet in our solar system?",
                options: ["Mars", "Jupiter", "Earth", "Venus"],
                correctAnswer: "Jupiter"
            },
            {
                question: "What is the chemical symbol for water?",
                options: ["H2O", "CO2", "NaCl", "O2"],
                correctAnswer: "H2O"
            }
        ];

        let currentQuestion = 0;
        let score = 0;

        const questionElement = document.getElementById("question");
        const optionsElement = document.getElementById("options");
        const resultElement = document.getElementById("result");
        const nextButton = document.getElementById("next-button");

        function loadQuestion() {
            const currentQuizData = quizData[currentQuestion];
            questionElement.innerText = currentQuizData.question;

            optionsElement.innerHTML = ""; // Clear previous options

            currentQuizData.options.forEach(option => {
                const button = document.createElement("button");
                button.innerText = option;
                button.addEventListener("click", () => checkAnswer(option));
                optionsElement.appendChild(button);
            });
        }

        function checkAnswer(answer) {
            const currentQuizData = quizData[currentQuestion];
            if (answer === currentQuizData.correctAnswer) {
                score++;
                resultElement.innerText = "Correct!";
                resultElement.style.color = "#28a745"; // Green for correct
            } else {
                resultElement.innerText = `Incorrect. The correct answer was: ${currentQuizData.correctAnswer}`;
                resultElement.style.color = "#dc3545"; // Red for incorrect
            }

            // Disable all buttons after an answer is selected
            const buttons = document.querySelectorAll(".options button");
            buttons.forEach(button => button.disabled = true);

            nextButton.style.display = "block"; // Show the next button
        }

        function nextQuestion() {
            currentQuestion++;

            if (currentQuestion < quizData.length) {
                loadQuestion();
                resultElement.innerText = ""; // Clear the result message
                nextButton.style.display = "none"; // Hide the next button again
            } else {
                // Quiz is over
                questionElement.innerText = "Quiz completed!";
                optionsElement.innerHTML = ""; // Clear options
                resultElement.innerText = `Your final score: ${score} out of ${quizData.length}`;
                nextButton.style.display = "none"; // Hide the next button
                resultElement.style.color = "#333";
            }
        }

        // Event listener for the next button
        nextButton.addEventListener("click", nextQuestion);

        // Initial load of the first question
        loadQuestion();

    </script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer Structure:**  The code is now properly structured into HTML, CSS, and JavaScript sections, making it much easier to read and understand.  The HTML creates the basic layout, the CSS styles it, and the JavaScript handles the quiz logic.
* **Question Data:** The `quizData` array is defined to hold the questions, options, and correct answers.  This makes it easy to add, remove, or modify questions.
* **Dynamic Question Loading:**  The `loadQuestion()` function dynamically updates the question text and creates buttons for each option. This eliminates the need for hardcoded HTML for each question.
* **Answer Checking:** The `checkAnswer()` function checks if the selected answer is correct and updates the score accordingly. It also provides feedback to the user ("Correct!" or "Incorrect.") and displays the correct answer if the user was wrong.  Crucially, it disables the answer buttons after an answer is chosen and displays the "Next Question" button.
* **Next Question Logic:** The `nextQuestion()` function advances to the next question or displays the final score if the quiz is complete.  It also hides the 'Next Question' button until an answer is given.  This is very important for a good user experience.
* **Event Listeners:**  Uses `addEventListener` to handle button clicks (answer selections and moving to the next question). This is the modern and preferred way to handle events in JavaScript.
* **CSS Styling:**  Includes CSS to make the quiz visually appealing and responsive.  Uses flexbox for centering the quiz container.  Includes `:hover` effects for buttons.
* **Improved User Experience:**  The quiz now provides clear feedback (correct/incorrect), displays the correct answer when the user is wrong, and prevents the user from selecting multiple answers for a single question.  The "Next Question" button appears only after an answer has been given. The buttons now have left-aligned text.
* **Concise Code:** Avoids unnecessary code and uses modern JavaScript features.
* **Comments:** The code is well-commented to explain each section.

How to Run this Code:

1.  **Save the code:** Copy the entire code block above and save it as an HTML file (e.g., `quiz.html`).  Make sure your text editor saves it with the `.html` extension.

2.  **Open in a browser:**  Double-click the `quiz.html` file to open it in your web browser (Chrome, Firefox, Safari, Edge, etc.).

The quiz should now be displayed in your browser, and you can start answering the questions.
👁️ Viewed: 8

Comments