The addEventListener() method attaches an event handler to the specified element.
Syntax
element.addEventListener(event, function, useCapture)Note: The third parameter use capture is usually set to false as it is not used.
Example
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>DOM Location host Property</title>
<style>
h1 {
color: green;
}
h2 {
font-family: Impact;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>addEventListener() method</h2>
<p>
This example uses the addEventListener()
method to add many events on the same
button.
</p>
<button id="myBtn">Try it</button>
<!--Driver Code Ends-->
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>"
this.style.backgroundColor = "red"
}
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>"
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>"
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- The code uses the addEventListener() method to attach multiple events (mouseover, click, and mouseout) to the same button and executes different functions for each event.
- When the user interacts with the button, the corresponding event message is displayed in the <p> element, and the button background color changes when the mouse hovers over it.