michael-h.dk

Multimedia Designer and Web Developer

Photo by Kobu Agency on Unsplash.com

Propagation, Bubbling and Once

When you make an application, sometimes you nedde to get some input from the user. In Javascript, you most likely will use the addEventListener, and make a callback function fire when the user interacts.

What I didn't know (among a lot of things) was, that it is not only the element that have the eventListener added, that are affected byt the user action, but all of the parents to the element are registering the action.

It is not something you normally notice, and normally it is not a problem, but if you have some nested elements with an eventListener, you will see this happend.

I will try to make a small demostaration here. I hope it makes any sense.

If this have spiked your interest, you can find a great article here on Medium, where Vaibhav Sharma explain this in a really good way,

Event Bubbling

When you have some nested elements, with the same sort of eventListener attached, the effect of the user interaction will bubble up the chain.

Here we have 3 divs nested inside each other, and with the bubbeling, when you click on the one on the inside, the otheres will also register the click.

The Code

const allDivs = document.querySelectorAll('.exDivs');

function changeColor(event) {
 this.classList.add('reverseColor');
}

allDivs.forEach(div => div.addEventListener('click', changeColor));

Click Me

Click Me

Click Me

Stop Propagation

You can prevent this to happend by adding a stopPropagation for the event in your code.

The Code

const allDivs = document.querySelectorAll('.exDivs');

function changeColor(event) {
event.stopPropagation();
 this.classList.add('reverseColor');
}

allDivs.forEach(div => div.addEventListener('click', changeColor));

Click Me

Click Me

Click Me

Once

If you have an element on a page, you weant to be sure only can be used one time, you can add the Once option to your eventlistener. After the function have run onetime, the eventlistener will be removed. From the documentation on MDN:

once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

The code:

element.addEventListener('click', runFunction, {once: true});