Event bubbling in JS

Hello guys, sorry to disturb you all; in order to stop an event from propagating to its parent element, we can use the following code:
const container = document.querySelector('#container');
const output = document.querySelector('#content');
const btn = document.querySelector('button');

function handleClick(e){
// e.stopPropagation();
output.textContent += `You clicked on the ${e.currentTarget.tagName} element!\n`;
// e.stopPropagation();
}

document.body.addEventListener('click', handleClick);
container.addEventListener('click', handleClick);
btn.addEventListener('click', handleClick);
const container = document.querySelector('#container');
const output = document.querySelector('#content');
const btn = document.querySelector('button');

function handleClick(e){
// e.stopPropagation();
output.textContent += `You clicked on the ${e.currentTarget.tagName} element!\n`;
// e.stopPropagation();
}

document.body.addEventListener('click', handleClick);
container.addEventListener('click', handleClick);
btn.addEventListener('click', handleClick);
My question is, does the order in which we write the line e.stopPropagation(); matters please
7 Replies
Jochem
Jochem3w ago
no, it can be anywhere as long as it's executed before the end of the codeblock
glutonium
glutonium3w ago
tho i would say putting at the beginning makes more sense. that's more intuitive imo
Jochem
Jochem3w ago
more readable too
Faker
Faker3w ago
yep got it, thanks !
Jochem
Jochem3w ago
(the main use for not having it at the top would be a conditional bubble stop, btw. Either based on general app state, or on the actual element being targeted not meeting certain criteria where the parent might)
Faker
Faker3w ago
ahh yeah I see, like we can execute the stopPropagation based on some kind of conditions
Eighth
Eighth3w ago
You can use checking which of the elements was clicked, sometimes a useful option
Want results from more Discord servers?
Add your server