Event Listeners in Javascript

Masum Ahmed
2 min readDec 9, 2020

--

As a beginner many of you might have came across this function called “addEventListener()” So, what is this bird call EventListener ? what is it’s purpose? How does it makes our life easier? and what’s so cool about it..In this blog post we will try to manoeuvre through some of the answers….

addEventListener is function that embeds an event(read a codeflow) to an element in the HTML page that appears on the client side.Now what is an “event”? To understand things better let us bisect this term “addEventListener”

The first word “add” , which as it means to add something , or embed something to an entity

To next word in our anatomy is “event”. An event in terms of web development would mean anything that occurs on the HTML document either due to action of client or triggered automatically is called an event. Like a “click” on some button in the web page, or scrolling of web page or hovering over specific area like nav bar..Now an event on a web page is not just limited to these few examples, there is a never ending list of events that can happen on a web page , you can have a read about them on this link: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

The last word in our today’s anatomy class is “listener” , the last words sums up the whole meaing of “addEventListner”, so a listener listner basically records an occuring on the webpage(event) and responds to it by triggering an action which the programmer wants to happen on that particular occurence. Basically the job of addEventListener() is to record a particular occurrence in the HTML document and further trigger a particular code flow (function) respective to that particular occurrence

Let us take a an example, when you visit a web page,on clicking the “submit” you get an alert message saying..”Successfully submitted” so, who’s the hero behind this process? No prizes for guessing! yes it’s the Event Listener doing it’s work..clicking submit button is the event here and getting the alert message is the response that it gives on listening to this event!

The syntax of an event listener is as follows :

element.addEventListener(“click”, myFunction);

function myFunction() {
alert (“Hello World!”);
}

P.S: This is my first attempt on writing a technical blog,i just loved writing it down ..Being first timer I ,know there are lot of mistakes so your feed is much appreciated

Thanks!

--

--

No responses yet