← Nivel 2: Mago

Lección 6 de 8 ⏱ 40 minutos

Un quiz para tus visitantes

Preguntas, respuestas y puntuación. En miniatura, aprenderás la lógica detrás de cada juego.

Cómo funcionará

Construirás un quiz: una pregunta, tres opciones, clic para responder, y al final aparece la puntuación. Los datos del quiz (preguntas y respuestas) vivirán en un array de objetos: suena sofisticado, pero verás que es solo una lista bien organizada.

Te lo muestro: los datos del quiz

const questions = [
  {
    text: "How many legs does a spider have?",
    choices: ["6", "8", "10"],
    correct: 1,
  },
  {
    text: "Which animal is the fastest?",
    choices: ["cheetah", "falcon", "hare"],
    correct: 1,
  },
  {
    text: "What's the name of our website?",
    choices: ["Code with Martin", "Code with Charlie", "Web with Wendy"],
    correct: 0,
  },
];

Te lo muestro: el motor del quiz

HTML:

<div class="card">
  <h2 id="quiz-question"></h2>
  <div id="quiz-choices"></div>
  <p id="quiz-status"></p>
</div>

JavaScript:

const questionEl = document.getElementById("quiz-question");
const choicesEl = document.getElementById("quiz-choices");
const statusEl = document.getElementById("quiz-status");

let questionNumber = 0;
let points = 0;

function showQuestion() {
  const question = questions[questionNumber];
  questionEl.textContent = question.text;
  choicesEl.innerHTML = "";   // clear the old buttons

  question.choices.forEach((choice, index) => {
    const button = document.createElement("button");
    button.textContent = choice;
    button.addEventListener("click", () => answer(index));
    choicesEl.appendChild(button);
  });

  statusEl.textContent = "Question " + (questionNumber + 1) + " of " + questions.length;
}

function answer(index) {
  if (index === questions[questionNumber].correct) {
    points++;
  }

  questionNumber++;

  if (questionNumber < questions.length) {
    showQuestion();
  } else {
    questionEl.textContent = "Done! 🎉";
    choicesEl.innerHTML = "";
    statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
  }
}

showQuestion();

Cosas nuevas:

Ahora tú 💪

Construye un quiz con tus propias preguntas: al menos cinco. Ideas para tu proyecto:

Solo cambia el contenido del array questions: el motor del quiz sigue igual. ¡Por eso los datos y la lógica van separados!

Extra: feedback de colores para las respuestas

¿Quieres que la respuesta correcta brille en verde? Ajusta answer para colorear los botones primero y mostrar la siguiente pregunta después de un segundo:

function answer(index) {
  const buttons = choicesEl.querySelectorAll("button");
  const correct = questions[questionNumber].correct;

  buttons[correct].style.backgroundColor = "#16a34a";
  if (index !== correct) {
    buttons[index].style.backgroundColor = "#dc2626";
  } else {
    points++;
  }

  setTimeout(() => {
    questionNumber++;
    if (questionNumber < questions.length) {
      showQuestion();
    } else {
      questionEl.textContent = "Done! 🎉";
      choicesEl.innerHTML = "";
      statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
    }
  }, 1000);
}

setTimeout(() => {...}, 1000) significa «ejecuta esto después de 1000 milisegundos». Y style.backgroundColor cambia CSS directamente desde JavaScript.

✅

Compruébalo tú: El quiz hace preguntas una tras otra, lleva la puntuación y muestra el resultado al final. Acabas de escribir tu primera aplicación de verdad: tiene datos, lógica e interfaz de usuario.

Lo que te llevas de esta lección