Introduction to Event Listeners in JavaScript ๐๐ค
addEventListener()
method in JavaScript
What is addEventListener?
Event listeners are among the most frequently used JavaScript structures in web design. Event Listners are the one which supports in the DOM when you respond to something in the site. Basically EventListener are actions that happens in the system.
For example
buttonTranslate.addEventListener("click", clickhandler);
You can add event listeners to any DOM object
When using the addEventListener() method, the JavaScript is separated from the HTML,So everytime you don't need to make changes in HTML page instead you can easily change it in javaScript
The most common events you might listen out for are load, click, touchstart, mouseover, keydown, etc.
- You can easily remove an event listener by using the removeEventListener() method.
Syntax
element.addEventListener(event, function);
First parameter is HTML DOM Event.
Second parameter is when we want to call a function when the event is listened.
Adding with simple event listener
Below example will explain how to use addEventListener()
HTML
<div id="output">
<p id="first">one</p>
<p id="second">two</p>
</div>
JavaScript
function modifyText() {
var second = document.getElementById("second");
if (second.firstChild.nodeValue == "three") {
second.firstChild.nodeValue = "two";
} else {
second.firstChild.nodeValue = "three";
}
}
var element = document.getElementById("output");
element.addEventListener("click", modifyText, false);
In the output you will observe two things:
- When you click on 'one' nothing will change as we are changing it for second element here in the code.
- You will see that when you click on the second element 'two' it changes to 'three' and vice versa!
How to know how many event listeners are there on page?
The best way to do this in Chrome is to use getEventListeners, which is part of the devtools API.
You can use document.querySelectorAll('*')
to grab all elements on a page, and run them each through getEventListeners to get their event listeners
Conclusion
Thats it for today. We saw the basic introduction of what event listeners are and how to add them to our website.
Connect with me on
- github: @samyakshah3008
- twitter: @SamyakShah_18
- linkedin: @samyakshah3008