A.R.
A.R.

Reputation: 15704

stopPropagation breaks event handler

I have a bit of a head scratcher when it comes to using stopPropagation in javascript. According to many different sources stopPropagation should stop bubbling of the event to parent elements, however, when I use it it seems to stop the event from being called after the first click. I have worked up a very simple bit of code to reproduce the behaviour below:

HTML:

<div id="root">
    <div id="top">
         <h1>Click Me!</h1>

    </div>
</div>

js/jQuery:

var myEvent = document.createEvent("Event");
myEvent.initEvent("boop", true, true);

$("#root").on('boop', function (e) {
    alert("root boop!");
});

$("#top").on('boop', function (e) {
    // After this is called, this event handler will never fire again.
    e.stopPropagation();
    alert("top boop!");
});

$("h1").click(function (e) {
    $("#top").get(0).dispatchEvent(myEvent);
    // I know that $("#top").trigger will prevent the problem, what is wrong with the form above?

});

There is a Fiddle as well.

Upvotes: 0

Views: 427

Answers (1)

mbillard
mbillard

Reputation: 38882

You dispatch myEvent on which you eventually call .stopPropagation(). Every click thereafter use the same instance of myEvent on which the propagation has been stopped.

You'll need to make a copy of the event before dispatching it if you want to be able to click multiple times.

...or you could rewrite your JavaScript like this:

$("#root").on('boop', function (e) {
  alert("root boop!");
});

$("#top").on('boop', function (e) {
  e.stopPropagation();
  alert("top boop!");
});

$("h1").click(function (e) {
  var myEvent = document.createEvent("Event");
  myEvent.initEvent("boop", true, true);
  $("#top").get(0).dispatchEvent(myEvent);
});

Working JS Fiddle

Upvotes: 3

Related Questions