AddEventListener Two Functions

I was wondering if addEventListener can have two functions inside it. I tried, but it didn't seem to work. Please give me a simple example if possible.

Thanks,

Alex

+6
source share
2 answers

Wrap your functions in functions.

function invokeMe() { console.log('I live here outside the scope'); } function alsoInvokeMe() { console.log('I also live outside the scope'); } element.addEventListener('event', function() { invokeMe(); alsoInvokeMe(); }); 
+20
source

The two main differences between the old model and the new event of the DOM Level 2 model are that 1) the new model does not depend on the specific property of the event handler and 2) you can register several functions of the event handler for any event on any one object. (From: Learning JavaScript) For example:

 <!DOCTYPE html> <html> <body> <div id="myElement"> Please click here.</div> <script> function func0() { alert("Function0 is called"); } function func1() { alert("Function1 is called"); } document.getElementById("myElement").addEventListener("click", func0, true); document.getElementById("myElement").addEventListener("click", func1, true); </script> </body> </html> 

How even you can remove a specific event handler function for a single event on any one object. For instance:

 <!DOCTYPE html> <html> <body> <div id="myElement"> Please click here.</div> <script> function func0() { alert("Function0 is called"); } function func1() { alert("Function1 is called"); } document.getElementById("myElement").addEventListener("click", func0, true); document.getElementById("myElement").addEventListener("click", func1, true); document.getElementById("myElement").removeEventListener("click", func0, true); </script> </body> </html> 
0
source

Source: https://habr.com/ru/post/973079/


All Articles