← Nivel 2 – Mago

Lección 2 de 8 ⏱ 25 minutos

Tu primer hechizo: un botón que hace algo

La página reacciona a un clic por primera vez. Aprenderás a encontrar un elemento y escuchar eventos.

Te lo muestro: los tres pasos de cada hechizo

Casi todo lo que JavaScript hace en una página sigue tres pasos:

  1. Encontrar un elemento en la página (un botón, un título, una imagen…),
  2. escuchar un evento (un clic, pasar el ratón, escribir texto…),
  3. hacer algo (cambiar el texto, el color, ocultarlo, mostrarlo…).

Así se ve en código. En el HTML, añade un botón y un párrafo:

<button id="my-button">Click me</button>
<p id="greeting">Nothing has happened yet.</p>

Y en script.js:

// 1. Find the elements by their id
const myButton = document.getElementById("my-button");
const greeting = document.getElementById("greeting");

// 2. Listen for a click on the button
myButton.addEventListener("click", () => {
  // 3. Do something: change the paragraph's text
  greeting.textContent = "The spell works! 🎉";
});

Vamos a desglosar lo nuevo:

Ahora tú 💪

Añade tu primer hechizo a tu web. Elige uno según tu proyecto (o inventa el tuyo):

🏫 Web del cole – botón «¿Qué hay de comer hoy?»

HTML (en la página principal):

<button id="lunch-button">What's for lunch today?</button>
<p id="lunch"></p>

script.js:

const lunchButton = document.getElementById("lunch-button");
const lunch = document.getElementById("lunch");

lunchButton.addEventListener("click", () => {
  lunch.textContent = "Today: pizza and salad! 🍕";
});
🙋 Web personal – botón «Cuéntame un chiste»
<button id="joke-button">Tell me a joke</button>
<p id="joke"></p>
const jokeButton = document.getElementById("joke-button");
const joke = document.getElementById("joke");

jokeButton.addEventListener("click", () => {
  joke.textContent = "Why do programmers prefer dark mode? Because light attracts bugs! 😄";
});
🌍 Diario de viajes – botón «¿Adónde vamos ahora?»
<button id="where-button">Where are we going next?</button>
<p id="where"></p>
const whereButton = document.getElementById("where-button");
const where = document.getElementById("where");

whereButton.addEventListener("click", () => {
  where.textContent = "Packing our bags: we're headed to the beach in Greece! 🌊";
});
⚽ Web del club – botón «¿Cuándo es el próximo partido?»
<button id="match-button">When's the next match?</button>
<p id="match"></p>
const matchButton = document.getElementById("match-button");
const match = document.getElementById("match");

matchButton.addEventListener("click", () => {
  match.textContent = "Saturday at 10:00, home game vs. Riverside. Come cheer us on! 📣";
});

Extra: dale estilo a tu botón en CSS para que quede bien:

button {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 20px;
  border: none;
  border-radius: 999px;
  background-color: #1d4ed8;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #1e40af;
}
⚠️

¿No funciona? Abre la consola (F12). Los errores más comunes: 1) el id en HTML no coincide exactamente con el nombre en getElementById (hasta las mayúsculas importan), 2) el <script> no está al final de <body>, 3) falta un corchete – la consola te dirá el número de línea.

Compruébalo tú: Pulsas el botón y aparece texto en la página. Acabas de conectar los tres lenguajes de la web: HTML (el botón), CSS (el aspecto) y JavaScript (el comportamiento).

Lo que te llevas de esta lección