Skip to content

Commit 3667165

Browse files
committed
learn about Event Propagation
1 parent 50910cf commit 3667165

File tree

2 files changed

+134
-0
lines changed

2 files changed

+134
-0
lines changed

Working-with-Events/README.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
| [Supported Event Types](#supported-event-types) |
1010
| [Working with `preventDefault()`](#working-with-preventdefault) |
1111
| [Understanding 'Capturing' & 'Bubbling' Phases](#understanding-capturing--bubbling-phases) |
12+
| [Event Propagation and `stopPropagation()`](#event-propagation-and-stoppropagation) |
1213

1314
## [Introduction to Events in JavaScript](https://drive.google.com/uc?export=view&id=1tfi-wZ9BYL2wISnyZ2JCcutRPApHpyCV)
1415

@@ -453,3 +454,134 @@ Readings:
453454
- [Bubbling and capturing](https://javascript.info/bubbling-and-capturing)
454455
455456
- [Deep dive into JavaScript event bubbling and capturing](https://blog.logrocket.com/deep-dive-into-event-bubbling-and-capturing/)
457+
458+
## Event Propagation and [`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
459+
460+
Now, this entire process of having multiple listeners for the same event because the event does not just trigger on the element itself but also on ancestors, that's called propagation.
461+
462+
Event propagation is the process of propagating an event from its source to its target in the Document Object Model (DOM) tree. Event propagation can occur in two ways: bubbling and capturing which we have discussed earlier.
463+
464+
Event propagation can be controlled by calling the [`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) method on the event object. When this method is called, the event is prevented from propagating any further. For example, if a button is clicked and the [`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation) method is called on the event object inside one of the event listeners, the event will not be triggered on any parent elements of the button.
465+
466+
Here's an example that demonstrates event propagation:
467+
468+
```HTML
469+
<div id="outer">
470+
<div id="inner">
471+
<button id="button">Click me</button>
472+
</div>
473+
</div>
474+
```
475+
476+
```javascript
477+
const outer = document.getElementById('outer');
478+
const inner = document.getElementById('inner');
479+
const button = document.getElementById('button');
480+
481+
outer.addEventListener('click', function() {
482+
console.log('Outer element clicked');
483+
});
484+
485+
inner.addEventListener('click', function() {
486+
console.log('Inner element clicked');
487+
});
488+
489+
button.addEventListener('click', function(event) {
490+
console.log('Button clicked');
491+
event.stopPropagation();
492+
});
493+
```
494+
495+
In this example, we have an outer `div` element, an inner `div` element, and a button element. We add event listeners to each element to log messages to the console when they are clicked. We also call the `stopPropagation()` method on the event object when the button is clicked.
496+
497+
When the user clicks on the button, the following messages will be logged to the console:
498+
499+
```
500+
Button clicked
501+
```
502+
503+
As we can see, the `click` event first triggers on the button, However, because we called the `stopPropagation()` method inside the event listener for the button, the event is not propagated any further up the DOM tree.
504+
505+
**[`stopImmediatePropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation)**
506+
507+
The `stopImmediatePropagation()` method is similar to `stopPropagation()`, but it not only stops the propagation of the current event, it also prevents any further listeners of the same event from being executed.
508+
509+
Here's an example:
510+
511+
```HTML
512+
<!DOCTYPE html>
513+
<html lang="en">
514+
<head>
515+
<title>
516+
stopPropagation() & stopImmediatePropagation()
517+
</title>
518+
<meta charset="UTF-8">
519+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
520+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
521+
<style>
522+
#one {
523+
width: 300px;
524+
height: 300px;
525+
background-color: orange;
526+
}
527+
#two {
528+
width: 200px;
529+
height: 200px;
530+
background-color: lightblue;
531+
}
532+
#three {
533+
width: 100px;
534+
height: 100px;
535+
background-color: pink;
536+
}
537+
</style>
538+
</head>
539+
<body>
540+
<h1>Event Methods</h1>
541+
<div id="one"> 1
542+
<div id="two"> 2
543+
<div id="three">
544+
3
545+
</div>
546+
</div>
547+
</div>
548+
<script>
549+
function div1(e) {
550+
this.style.backgroundColor = 'red';
551+
}
552+
function div2(e) {
553+
this.style.backgroundColor = 'blue';
554+
e.stopPropagation(); // Stop the event from bubbling up to parent elements
555+
// e.stopImmediatePropagation(); // Stop the event from bubbling up to parent elements and prevent other event handlers from being called
556+
}
557+
function div2_2(e) {
558+
this.style.width = '250px';
559+
560+
}
561+
function div3(e) {
562+
this.style.backgroundColor = 'green';
563+
}
564+
const divOne = document.getElementById("one");
565+
const divTwo = document.getElementById("two");
566+
const divThree = document.getElementById("three");
567+
divOne.addEventListener('click', div1);
568+
divTwo.addEventListener('click', div2);
569+
divTwo.addEventListener('click', div2_2);
570+
divThree.addEventListener('click', div3);
571+
</script>
572+
</body>
573+
</html>
574+
```
575+
576+
In this example, we have three nested `div` elements with different background colors. When we click on the innermost div (with id "three"), the `click` event will be triggered and will propagate up to its parent elements (divs with ids "two" and "one"). We have attached event listeners to each of these elements, which will change their background colors when the `click` event is triggered.
577+
578+
The event listener attached to the div with id "two" uses the `stopPropagation()` method to stop the event from bubbling up to its parent element (div with id "one"). As a result, the event listener attached to the div with id "one" is not triggered, and its background color remains unchanged.
579+
580+
If we replace the `stopPropagation()` method with `stopImmediatePropagation()`, then the event listener attached to the div with id "two" will also prevent other event handlers from being called. In this case, the second event listener attached to the div with id "two" will not be triggered, and the width of the div with id "two" will not be changed.
581+
582+
> Note
583+
> Some events in the DOM do not propagate. These events are known as non-bubbling events or non-propagating events. These events cannot be captured or bubble up the DOM tree. Examples of non-bubbling events include focus, blur, load, unload, reset, submit, change, input etc. Check official docs for more information.
584+
585+
Readings:
586+
587+
- [StopPropagation vs. StopImmediatePropagation in JavaScript](https://betterprogramming.pub/stoppropagation-vs-stopimmediatepropagation-in-javascript-27b9f8ce79b5)

Working-with-Events/projects/events-01-starting-setup/assets/scripts/events.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ div.addEventListener('click', event => {
6161

6262
button.addEventListener('click', event => {
6363
console.log('CLICKED BUTTON');
64+
event.stopPropagation();
65+
// event.stopImmediatePropagation();
6466
console.log(event);
6567
});
6668

0 commit comments

Comments
 (0)