addEventListener Two Functions
51,801
Solution 1
Wrap your functions in a function.
const invokeMe = () => console.log('I live here outside the scope');
const alsoInvokeMe = () => console.log('I also live outside the scope');
element.addEventListener('event',() => {
invokeMe();
alsoInvokeMe();
});
Solution 2
Two major differences between the older model and the newer DOM Level 2 event model is that 1) the newer model isn’t as dependent on a specific event handler property, and 2) you can register multiple event handler functions for any one 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>
As, even you can remove a specific event handler function for one event on any one object. 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);
document.getElementById("myElement").removeEventListener("click", func0, true);
</script>
</body>
</html>
Related videos on Youtube
![Alex](https://i.stack.imgur.com/5XUUK.png?s=256&g=1)
Author by
Alex
Updated on October 18, 2020Comments
-
Alex over 3 years
How can I make it so that addEventListener() has two functions inside it?
I have tried finding my own solution, but none seem not to work. Please give me example if it is possible.