JavaScript addEventListener()

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Syntax of addEventListener() in JavaScript

Parameters of of JavaScript addEventListener()

The method addEventListener in javascript takes two compulsory parameters the third being optional

  • event : a string indicating the event type to listen for.
  • function() : the function which we want to execute once the event has happened
  • useCapture : a boolean value that is by default set to false, and is used to control event propagation, here the value true indicates the event capturing phase and false indicates the event bubbling phase, it is an optional parameter

Return Value of addEventListener() in JavaScript

JavaScript addEventListener()

Exceptions of of JavaScript addEventListener()

There are no specific exceptions to the method addeventlistener in javascript

Example of addEventListener() in JavaScript

In the below example, we are listening to the click event on a button element and are executing a callback function in response for that.

Output:

Before clicking on the Click Here button -

CLICK HERE EVENTLISTNER

After clicking on the Click Here button -

IMAGE HELLOWORLD

Explanation -

  • Here, in the HTML body, we have two elements, a button and a paragraph with respective id's as "click-here" and "text-to-show"
  • Using javascript we are capturing the element whose id is "click-here" ie. the button, and we are applying addEventListener()on that to listen for a click on this element, ie to listen if the user clicks on this button
  • And when clicked, we are executing an arrow function and within that, we are capturing the element whose id is "text-to-show" meaning our paragraph and then setting its innerText ie. the text it will enclose as "Hello World"

How does JavaScript addEventListener() Work?

The method addeventlistener in javascript listens to a particular event being happening on a specified element, and if it happened, then it executes certain code in response for that ie. the addEventListener() method attaches an event handler to an element and executes a certain set of codes on the successful happening of the specified event. These events can be user-generated or they can be a response from an external API.

The addEventListner() method is not only limited to being applied on HTML and SVG elements, rather it can be applied to any DOM object, even the object window itself.

Note - Using prefixes like on etc. with the event's name should be avoided, meaning we should be writing click instead of onClick

More Examples of JavaScript addEventListener()

1. Applying multiple Event Listeners on the same Element

We can add multiple event listeners on the same element without altering the functionality of previously defined event listeners, Lets understand this with the help of an example.

Output:

Before happening of event

BEFORE EVENT

After happening of the events

AFTER EVENT

Explanation -

  • Similarly to the above, we have two HTML elements, a button, and a paragraph
  • Using JavaScript, we are listening for various events being happening on the specified button element
  • Here in the above code, we are listening for, if the user makes a click event on the button, ie. if the user clicks on the button element, then we are setting the innerText of the paragraph as "Hello World". If the user's mouse has hovered over the button, then we are setting the innerText as "Hello World again" and if the mouse of the user is hovered out of the button, then we are setting the paragraph's innerText as "Hello World once again"

2. Passing Parameters to a Function when an Event Occurs

We can not only execute simple functions when an event has occured, infact we can also pass parameters to a function and then can do some complex calculation as well in response for that event's occurence. See the below example, here we are multiplying two numbers by passing as a parameter to the response function of the click event and are showing the result when the click here butotn is clicked

Output:

Before clicking on the Click Here button

BEFORE CLICK

After clicking on the Click Here button

AFTER CLICK

3. Example on Event Capturing and Bubbling in JavaScript addEventListener()

Suppose in our HTML, there is a case, where we have a div element and inside that, we also have a paragraph element and we have added Event Listeners on both of them, and now in this case, which event Listener will be executed first? The answer is, this is where we use the third optional parameter of the addEventListener() function, the useCapture parameter. If it is marked as true then the parent's event handler will be executed first followed by the subsequent child event handlers ie. from outerwards to inwards, and if its market as false, then the child's event listener will be executed first followed by the parent's listener By default the value of useCapture in the addEventListener() method is false which means event bubbling will be happening.

Let's understand it through the code

Case 1 - The useCapture parameter is omitted, hence it takes the value as false by default, meaning event bubbling will happen

Output

Before clicking on the Click Here button

BEFORE CLICKING

After clicking on the Click Here button

AFTER CLICKING

Case 2 - The useCapture parameter is assigned the value as true, meaning event capturing will happen

Output:

Before clicking on the Click Here button

PARENTHELLO

After clicking on the Click Here button

WORLDCHILD

Note - Assigning true and false as the third parameter is only logical for the parent element, passing any of the above to the child element, will have no additional effect

4. Adding an event handler to the window object

Here, we are adding an event handler to window object, ie the browser window and are randomly showing Mathematical numbers whenever the user zooms in or zooms out the browser.

Output:

Before resizing the window

BEFORE RESIZING

After resizing the browser window

AFTER RESIZING

5. removeEventListener() method

We can also remove any specific event listening, on any specified element using removeEventListener() method. removeEventListener() method takes two parameters, the first being the event which we want to stop listening for that specific element and the second parameter being a function which we would be executing if that event would happen.

Output:

Before the happening of the events

BEFOREEVENT

After the happening of the events

AFTEREVENT

We can see here that, the listening of the mouseover event on the button element has been removed.

Supported Browsers

Browser NameSupported on versions
Mozila Firefoxversion >= 2 (Oct 2006)
Safariversion >= 3.1 (Mar 2008)
Google Chromeversion >= 4 (Jan 2010)
Internet Explorerversion >= 9 (Mar 2011)
Microsoft Edgeversion >= 12 (Jul 2015)

Conclusion

  • The addEventListener() method adds an event handler to the specified element which gets executed on the successful happening of the mentioned event
  • We can add multiple event listeners to the same element without overriding the others, ie. all the added handlers will be functional along with each other
  • Events handlers are not only limited to HTML elements but can be applied to any DOM object
  • addEventListner() method makes it easier for us to manage how our program will respond to bubbling and capturing events
  • Any event listener can be easily removed using the removeEventListner() method