-1

I think this is best asked with code:

var event = new CustomEvent("custom", {bubbles: true}); // Create Event

// Create and attach element
var element = document.createElement("div");
document.body.appendChild(element);

element.addEventListener("custom", function(e) {
    console.log("listening");
});

// At this point I thought that if the "custom" event were fired that my  
// element listing would be triggered with the listener callback.
// But.... 

document.body.dispatchEvent(event);
// check the console... nothing :(

// the only way I am able to get my element event listener to fire is if 
// the element calling the dispatchEvent(event) is the element itself.
element.dispatchEvent(event);

What am I doing wrong? Is this the way events are meant to work? My question is how do I listen to a custom event when the event is not dispatched

dispatchEvent(event)

from the element containing the listener callback

element.addEventListener("custom", function(){});

1 Answers1

1

You have to dispatch the event on the element that is actually listening for it, or an element lower in the chain if it's supposed to bubble.

You can't listen for the event on a DIV, and then dispatch the event on the BODY tag, and expect it to bubble downwards

element.dispatchEvent(event);

Is the proper way to fire the event, it won't bubble from the body to a child, events only bubble upwards the DOM chain.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • To add to this... You could, conversely, apply your listener to the document body instead, and it would fire whether the event is triggered on the body OR the element. – relic Jul 01 '16 at 21:17
  • @relic - of course, if the event listener was on the body, triggering the event on the body, or any child thereof, would fire the event handler. – adeneo Jul 01 '16 at 21:19
  • Right. I wasn't bringing it up to correct you or anything, just pointing it out for the benefit of the OP. – relic Jul 01 '16 at 21:21
  • that makes sense. Thanks. – Cory Mickelson Jul 02 '16 at 02:30