Do Si Do Si - 1 month ago 21
Javascript Question

Div event bubbling

I have in my project a window click eventListener and some click events on div elements. If i click on the div the click event on this div-element (correct) and the window click eventListener fires (not correct).

Can I bubble the div element that the window click eventListener do not fire the event?

For a better demonstration jsfiddle:



window.addEventListener('mouseup', onDocumentMouseUp, false);

function onDocumentMouseUp(event){
alert('dont fire this event on button click')
}

$('#button').on({
click: function (event) {
alert('button click event');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" style="height: 30px; width: 30px; background: blue"></div>





I hope somebody can help me.

Answer

Yes, you can use event.stopPropagation() like this:

$('#button').on({
  click: function (event) {
        alert('button click event');
        event.stopPropagation();
  }
});