Skip to main content

Exercise 29: Preventing Propagation with e.stopPropagation()

Discover how to use e.stopPropagation() to control event propagation in JavaScript and improve interaction logic. The primary goal is to learn how to prevent an event from propagating to parent elements usinge.stopPropagation()

Activity

  1. Create a containerdivthat contains a button.

  2. Add a click event to thedivthat displays a message in the console indicating that the container has been clicked.

  3. Add a click event to the button that displays a different message, and usee.stopPropagation()to prevent the button click from also triggering the eventdivcontainer.

  4. Observe howe.stopPropagation()It prevents the event from spreading to the container.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Evitar Propagación de Eventos con e.stopPropagation()</title>
</head>
<body>
<h1>Ejercicio 29: Evitar Propagación de Eventos con e.stopPropagation()</h1>

<div id="container" style="padding: 20px; background-color: #e0e0e0;">
Contenedor
<button id="innerButton">Botón Interno</button>
</div>

<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
// Evento para el contenedor
document.getElementById("container").addEventListener("click", () => {
console.log("Haz clic en el contenedor");
});

// Evento para el botón interno con e.stopPropagation()
document.getElementById("innerButton").addEventListener("click", (e) => {
e.stopPropagation();
console.log("Haz clic en el botón interno");
});
info

🔎Check the sectionDOM Events in JavaScriptwhere you will find more information on this topic.