본문으로 건너뛰기

Advanced Events

Advanced Events

When an event (e.g., a click, keyboard input, etc.) occurs on a web page, it propagates through the DOM tree in two phases known as capturing and bubbling.

Event Bubbling and Capturing

Event capturing and bubbling can be likened to a water droplet falling from the top of a tree (capturing) and then bouncing back up from the ground (bubbling).

1. Capturing: The event starts at the highest (parent) element and propagates down to the actual element where the event occurred. For example, when a click event occurs, it starts at the document object and is passed down sequentially to the target element.

2. Bubbling: The event starts at the actual element where it occurred and propagates up to the highest (parent) element. For example, when a button is clicked, the event is passed sequentially to higher elements such as the form the button is in, the section, and the body of the page.

Stopping Event Propagation

stopPropagation and preventDefault methods:

  1. stopPropagation: Stops the current event from propagating any further.

    • Example: The following code prevents a click event from bubbling up to higher elements.
    element.addEventListener('click', function (event) {
    event.stopPropagation();
    });

  1. preventDefault: Prevents the browser's default action (like clicking a link, submitting a form, etc.)
    • Example: The code below prevents the default action of navigating to a URL when a link is clicked.
    document.querySelector('a').addEventListener('click', function (event) {
    event.preventDefault();
    console.log("Link was clicked, but we're not navigating anywhere!");
    });

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!