DOM Event Listener
The addEventListener() method
This method mainly used in order to overcome the problem of not assigning multiple event handlers to one event.
With the help of this method, we can easily attach an event handler to an element without overwriting the existing one. By using, addEventListener method, we can add many event handlers of the same type to an element.
Syntax
element.addEventListener(event, function, useCapture);
Here, the first type is Events name example: “click” or “mouseover”.
The second type is the handler function, which is called when an event occurs.
The third one is an optional argument.
The removeEventListener() method
We also have a removeEventListener method, which is used in order to remove the handler.
Syntax
element.removeEventListener(event, function, useCapture);
Code:
Single Event Handler
<html>
<body>
<h1>DOM/HTML Events</h1>
<h2>The addEventListener method </h2>
<input type="Button" value="Click Me!" id="btn">
<script>
btn.addEventListener("click",fun);
function fun()
{
alert("Hello TutorialsLink!");
}
</script>
</body>
</html>
Output:
Multiple Event Handler
<html>
<body>
<h1>DOM/HTML Events</h1>
<h2>The addEventListener method </h2>
<input type="Button" value="Click Me!" id="btn">
<script>
btn.addEventListener("click",fun);
btn.addEventListener("click",fun1);
function fun()
{
alert("1st Event Handler");
}
function fun1()
{
alert("2nd Event Handler");
}
</script>
</body>
</html>
Output: