Frontend Development: Event Bubbling and Capturing

Peter Jeon·2023년 6월 20일
0

Frontend Development

목록 보기
22/80
post-custom-banner

Event Bubbling and Capturing

In JavaScript, when an event is fired on an element that is nested within other elements, the event is first captured down to the right target element, and then bubbled up again. This is called Event Bubbling and Capturing.

Understanding Event Bubbling

Event Bubbling

Event Bubbling is the propagation of the same event from the innermost target element to the outermost parent element.

document.querySelector("#parent").addEventListener('click', () => {
  alert('Parent Clicked!');
});

document.querySelector("#child").addEventListener('click', (event) => {
  alert('Child Clicked!');
  event.stopPropagation();
});

In this case, clicking on the child will first trigger the alert for the child, and then the alert for the parent due to event bubbling.

Understanding Event Capturing

Event Capturing is the process where the event starts from the outermost parent and goes down to the target child.

document.querySelector("#parent").addEventListener('click', () => {
  alert('Parent Clicked!');
}, true);  // set useCapture to true

document.querySelector("#child").addEventListener('click', (event) => {
  alert('Child Clicked!');
  event.stopPropagation();
});

In this case, clicking on the child will first trigger the alert for the parent, and then the alert for the child due to event capturing.

Preventing Event Bubbling or Capturing

We can prevent event bubbling or capturing by using event.stopPropagation(). This will stop the event from further propagation in the capturing/bubbling phase.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글