This example uses the addEventListener()
method to add two click events to the same button.
However, the stopImmediatePropagation()
method stops the second event handler from being executed.
<!DOCTYPE html> <html> <body> <button id="myBtn">Test</button> <p id="demo"></p> <script> function myFunction(event) {//from w ww . j av a2s. co m document.getElementById("demo").innerHTML = "Hello World!"; event.stopImmediatePropagation(); // Try to remove me } function someOtherFunction() { document.getElementById("demo").innerHTML = "I will not get to say Hello World"; } var x = document.getElementById("myBtn"); x.addEventListener("click", myFunction); x.addEventListener("click", someOtherFunction); </script> </body> </html>
The stopImmediatePropagation()
method prevents other listeners of the same event from being called.