javascriptdomeventsevent-handlingevent-propagation

Event Propagation - Is it possible to add several listeners to the same element for the same type of event?


https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation

The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called.

If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.

I found the method stopImmediatePropagation(), it causes me confusion to have several handlers for the same event, and even worse for the same element.

Could you give me a simple example?

Preferably in code please


Solution

  • The HTML5 specification has a nice example in the Event Handlers section that shows not only an event handler and multiple other event listeners attached to the same element for the same event, but also describes the slightly tricksy order in which they are run.

    <button id="test">Start Demo</button>
    <script>
     var button = document.getElementById('test');
     button.addEventListener('click', function () { alert('ONE') }, false);
     button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
     button.addEventListener('click', function () { alert('THREE') }, false);
     button.onclick = function () { alert('TWO'); };
     button.addEventListener('click', function () { alert('FOUR') }, false);
    </script>
    

    It says that on clicking the button, 'the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.'