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
-
Create a container
divthat contains a button. -
Add a click event to the
divthat displays a message in the console indicating that the container has been clicked. -
Add a click event to the button that displays a different message, and use
e.stopPropagation()to prevent the button click from also triggering the eventdivcontainer. -
Observe how
e.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.