Alcadur
Alcadur

Reputation: 685

HTMLElement Custom Event

I create a custom event ex. var event = new Event('hello');, add listener to nodes

div1.addEventListener('hello', /*cb1*/);
div2.addEventListener('hello', /*cb2*/);
div3.addEventListener('hello', /*cb3*/);

and how to dispatch my event? I would like to call event.dispatch() and cb1, cb2 and cb3 should be called

Upvotes: 0

Views: 59

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

Just create Event using new Event('hello'); and dispatch them one by one for each div.

div1.addEventListener('hello', function(){
  console.log( "Event called for " + this.id );
});
div2.addEventListener('hello', function(){
  console.log( "Event called for " + this.id );
});
div3.addEventListener('hello', function(){
  console.log( "Event called for " + this.id );
});

var event = new Event('hello');
div1.dispatchEvent( event );
div2.dispatchEvent( event );
div3.dispatchEvent( event );
<div>
  <div id="div1"></div>
  <div id="div2"></div>
  <div id="div3"></div>
</div>

Upvotes: 1

Related Questions