Skip to Content

Michael Hyland

Web Developer & Graphic Designer

Premium and cost-effective web solutions for small businesses and non-profits.

Contact → [email protected]

Easy Event Listeners + Event Bubbling: Work Smarter, Not Harder

"Event bubbling" refers to the process where an event triggered on a DOM element propagates through its parent elements. Consequently, each parent element with an event listener will react to the event. Within the event handling process, it's crucial to filter and specify which elements we intend to respond to.

Initially, this approach might appear slow and somewhat messy, but surprisingly, it's among the most adaptable and efficient


    document.addEventListener('click', function (event) {
        if (!event.target.matches('.btn-scroll-into')) return;
        console.time('bubbling');
        event.preventDefault();
        const element = document.getElementById(event.target.dataset.target);
        element.scrollIntoView();
        console.timeEnd('bubbling');
    });

In this setup, we utilize "addEventListener" on all elements to capture clicks across the entire DOM. The JavaScript code then scans through all the children to identify elements matching the class ".btn-scroll-into".

If the condition isn't met, we execute "return;", effectively halting the function. Otherwise, we proceed with the same code as previously implemented.

The event bubbling method is my go-to when dealing with numerous elements. Its simplicity makes it hassle-free to implement without concerns about performance bottlenecks.