DOM EventListener
The event listeners are used to any user events in the browser. Ex. button click is an example for an event.
We need to add an event listener to the event to fire and perform any action. The addEventListener() method is used to attach event handler to the element.
Syntax
element.addEventListener(event, function, useCapture);
Here, the first parameter is the event, which can be a click event or mouseover etc.
The second parameter is the function to be called when the event occurs.
The third parameter is an optional boolean value, which specifies whether to use event capture or event bubbline.
Example 1
<!DOCTYPE html>
<html>
<body>
<p>Example for event listener.</p>
<button id="btnSubmit">Submit</button>
<script>
document.getElementById("btnSubmit").addEventListener("click", onSubmit);
function onSubmit() {
alert("Form has been submitted.");
}
</script>
</body>
</html>
In the above example, we queried the button with id btnSubmit and added a click event using addEventListener.
The function that will be called on the click event is onSubmit.
Example 2
<!DOCTYPE html>
<html>
<body>
<p id="message">ReadersBuddy</p>
<script>
var x = document.getElementById("message");
x.addEventListener("mouseover", onMouseOver);
x.addEventListener("mouseout", onMouseOut);
function onMouseOver() {
document.getElementById("message").style.backgroundColor="red";
}
function onMouseOut() {
document.getElementById("message").style.backgroundColor = "white";
}
</script>
</body>
</html>
In the above example, we have attached event listener for mouseover and mouseout event.
The removeEventListener() method will remove the event handler attached to an element by addEventListener().
Example
<!DOCTYPE html>
<html>
<body>
<p>Example for event listener.</p>
<button id="btnSubmit">Submit</button>
<script>
document.getElementById("btnSubmit").addEventListener("click", onSubmit);
function onSubmit() {
alert("Form has been submitted.");
document.getElementById("btnSubmit").removeEventListener("click",onSubmit);
}
</script>
</body>
</html>
In the above example, once the button is clicked it will show an alert message. Once after that futher clicks on the button will never perform any action since we have removed the event handler using removeEventListener()).