Beispiel:JS-Multiple-Choice-Quiz-3.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" media="screen" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">  
<title>Multiple-Choice-Quiz - 3</title>
<style>
#quiz label {
	display: block;
	background-color: lightBlue;
	border: medium solid steelBlue;
      cursor: pointer;
      transition: background-color 0.2s, border-color 0.2s;
    }

    /* Hover-Effekt */
    #quiz label:hover {
      background-color: lightyellow;
    }

    /* mache Fokus sichtbar */
    #quiz input[type="radio"]:focus + label {
      outline: 2px solid black;
      outline-offset: 2px;
    }

    /* Auswahl */
    #quiz input[type="radio"]:checked + label {
      background-color: gold;
      border-color: #866a00;
    }

#quiz input {  /*visually-hidden */
    clip: rect(0 0 0 0);
    clip-path: inset(50%);
    height: 1px;
    overflow: hidden;
    position: absolute;
    white-space: nowrap;
    width: 1px;
}
#quiz label {
	border-radius: 0.2em;
	margin: 0.1em 0;
	padding: 1em 2em;
	max-width: 33em;
}
</style>
</head>

<body><h1>Multiple-Choice-Quiz - 3</h1>


<form id="quiz" action="">
	<p id="intro">Kennst du dich aus? Teste dein Wissen in diesem Multiple-Choice-Quiz!</p>
	<button type="submit">Starte Quiz!</button>
</form>
    
<template id="quizRadiogroup">
  <fieldset role="radiogroup">
    <legend>Frage …</legend>

    <input type="radio" name="answer" id="a27_0">
    <label for="a27_0">Antwort 1</label>

    <input type="radio" name="answer" id="a27_1">
    <label for="a27_1">Antwort 2</label>

    <input type="radio" name="answer" id="a27_2" value="Antwort 3">
    <label for="a27_2">Antwort 3</label>

    <input type="radio" name="answer" id="a27_3" value="Antwort 4">
    <label for="a27_3">Antwort 4</label>    
  </fieldset>
</template>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const JSONUrl = "/extensions/Selfhtml/example.php/Beispiel:Multiple-choice-questions.json";	
  const form = document.getElementById("quiz");
  const intro = document.getElementById("intro");
  const button = form.querySelector("button");
  const template = document.getElementById("quizRadiogroup");

  let questions = [];
  let currentQuestionIndex = 0;

  button.addEventListener("click", async function (e) {
    e.preventDefault();

    if (intro) {
      intro.remove();
      // Load and render quiz only on first click
      await loadQuestions();
      renderQuestion(currentQuestionIndex);
      button.textContent = "Auswahl bestätigen";
    } else {
      // Here you could evaluate the answer or go to the next question
      console.log("Answer submitted or next step...");
    }
  });

  async function loadQuestions() {
    try {
      const response = await fetch(JSONUrl);
      const data = await response.json();
      questions = data.data;
    } catch (error) {
      console.error("Fehler beim Laden der Fragen:", error);
    }
  }

  function renderQuestion(index) {
    const questionData = questions[index];

    // Clear any previous quiz elements (except the button)
    const oldFieldset = form.querySelector("fieldset");
    if (oldFieldset) oldFieldset.remove();

    // Clone the template
    const quizContent = template.content.cloneNode(true);
    const fieldset = quizContent.querySelector("fieldset");
    const legend = fieldset.querySelector("legend");

    // Set question text
    legend.textContent = `${questionData.category}: ${questionData.question}`;

    // Populate answers
    const answers = questionData.answers;
    fieldset.innerHTML = `<legend>${legend.textContent}</legend>`; // Reset content while keeping updated legend

    answers.forEach((answer, i) => {
      const inputId = `q${index}_a${i}`;

      const input = document.createElement("input");
      input.type = "radio";
      input.name = "answer";
      input.id = inputId;
      input.value = answer.answer;

      const label = document.createElement("label");
      label.htmlFor = inputId;
      label.textContent = answer.answer;

      fieldset.appendChild(input);
      fieldset.appendChild(label);
    });

    // Insert new quiz content before the button
    form.insertBefore(fieldset, button);
  }
});
</script>


<!--
document.addEventListener("DOMContentLoaded", () => {


    }

    // Move to the next question or show results
    function handleSubmit(event) {
      event.preventDefault();
      const selectedAnswer = quizForm.querySelector("input[name='q" + currentQuestionIndex + "']:checked");
      if (!selectedAnswer) {
        alertBox("Bitte wählen Sie eine Antwort aus!", "error");
        return;
      }

      const question = questions[currentQuestionIndex];
      const selectedValue = selectedAnswer.value;
      const selectedAnswerObj = question.answers.find(ans => ans.answer === selectedValue);

      if (selectedAnswerObj?.correct) {
        alertBox("Richtig! " + selectedAnswerObj.explanation, "success");
      } else {
        const correctAnswer = question.answers.find(ans => ans.correct);
        alertBox("Falsch! Die richtige Antwort ist: " + correctAnswer.answer + ". " + correctAnswer.explanation, "error");
      }

      currentQuestionIndex++;
      if (currentQuestionIndex < questions.length) {
        displayQuestion(currentQuestionIndex);
      } else {
        quizForm.innerHTML = "<p>Quiz beendet! Vielen Dank fürs Mitmachen!</p>";
      }
    }

    // Display the first question
    displayQuestion(currentQuestionIndex);

    // Handle form submission
    quizForm.addEventListener("submit", handleSubmit);
  }

  // Helper function for alerts
  function alertBox(text, type) {
    const alertBox = document.createElement("p");
    alertBox.textContent = text;
    alertBox.className = type || "";
    quizForm.appendChild(alertBox);
    setTimeout(() => {
      alertBox.remove();
    }, 3000);
  }

  // Start loading questions
  loadQuestions();
});

</script>-->


</body>
</html>