JavaScript for WordPress Forums Vanilla JavaScript Events: dispatchEvent()

This topic contains 1 reply, has 2 voices, and was last updated by  Zac Gordon 2 years, 5 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #27933

    bruno
    Participant

    Hi, Zac!

    I´m following your advice, and I´m trying to learn all that I can regardings to Events.

    I´m actually in this guide: http://javascript.info/dispatch-events, and there is something that I don´t fully understand, maybe you can give us a fresh example of what they say.

    I quote: “After an event object is created, we should “run” it on an element using the call elem.dispatchEvent( event ). Then the handler reacts on it as if it were a regular built-in event.

    They put the following example:

    <button id="elem" onclick="alert('Click!');">Autoclick</button>
    
    <script>
      let event = new Event("click");
      elem.dispatchEvent(event);
    </script>
    

    Let me add that I understand the Event Constructor(that they mention in the web page).

    What I don´t understand is the purpose of dispatchEvent, what is the difference (or how it relates) with addEventListener ??

    #28074

    Zac Gordon
    Keymaster

    Sorry for the delay on this!

    Since dispatching allows you to execute events and trigger their event listeners, that statement you quoted is just reminding you that you should attach the dispatch to the same element you attached the event listener to.

    Is that what you were asking?

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.