Matt Matt - 11 months ago 49
Javascript Question

can someone explain how this stopPropagation works?

I was trying to setup this "when you click outside of the element, close it" type of thing using some code I found on Stackoverflow:

$(document).click(function() {

$('.show-list-button').click(function(event) {

Could someone explain the later part with stopPropagation? I don't understand why it's needed.


Answer Source

Imagine this:



$('div').click(function() { alert('div clicked'); });
$('span').click(function() { alert('span clicked'); });

Check out what happens when you click each one

When you click the span, it happens to also trigger the div because your also clicking the div.

Now if we wanted to alert the span only we need to stop the div click from triggering when we click on the span so we do this:

$('div').click(function() { alert('div clicked'); });
$('span').click(function(e) { alert('span clicked'); e.stopPropagation(); });

See what happens now