22

I'm confused with the script below:

var event = new Event('shazam');

document.body.addEventListener('shazam',function(){
    alert('body');
});

document.addEventListener('shazam',function(){
    alert('document');
});

window.addEventListener('shazam',function(){
    alert('window');
});

document.body.dispatchEvent(event);

When I run this script on my browser, I just get the alert('body'); event. but if i set the capturing parameter of addEventListener (the third optional parameter) to true, all the alerts captured in order they should.

Why the shazam event doesn't bubble up ?

Shnd
  • 1,846
  • 19
  • 35

1 Answers1

43

You need to set the bubbles property to true, and you have to do this during the construction:

var event = new Event('shazam', { bubbles: true });

or the old way with initEvent, passing true as the second argument to allow bubble:

event.initEvent('shazam', true);

MDN Doc

Edric
  • 24,639
  • 13
  • 81
  • 91
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • Thank you for your brief response :) – Shnd Apr 13 '14 at 21:56
  • But one question: why bubbling is by default disabled in Event Object. – Shnd Apr 13 '14 at 21:57
  • 2
    It defaults to false as per https://dom.spec.whatwg.org/#interface-event (or, if you prefer, https://developer.mozilla.org/en-US/docs/Web/API/Event/Event ). I would guess this is to provide the option with the least potential side effects by default. – Brett Zamir Jul 09 '16 at 01:47