Hello Sunil
javaScript-addeventlistener-feature-image

AddEventListener JavaScript: What It Is and How To Use It

As a front-end developers, we make use of HTML and CSS to create static pages, but to add dynamic properties to such web pages, we need JavaScript. With JavaScript, we can introduce events and actions to a webpage to make for interactivity.

For example, sometimes, when we create a web page, we may want to execute a piece of code when someone triggers a particular type of activity on our website such as when a user clicks a button.

With the JavaScript addEventListener method, we can do it quickly and easily.

The JavaScript addEventListener() method allows us to set up functions to be called when a specified event happens, such as when a user clicks a button.

In this post, we will learn about addEventListener, a particular event handler in JavaScript.

We will cover its definition, syntax, and code example. In the end, you will learn how to remove the handler using removeEventlistener and some other concepts.

Let’s get to it. 

Understanding Events and Event Handlers

Events are actions that happen when the user or browser manipulates a page. They play an important role as they can cause elements of a web page to change dynamically.

For example, when the browser finishes loading a document, then a load event occurred. If a user clicks a button on a page, then a click event has happened.

Many events can happen once, multiple times, or never. You also may not know when an event will happen, especially if it is user generated.

In these scenarios, you need an event handler to detect when an event happens. This way, you can set up code to react to events as they happen on the fly.

addEventListener() makes it easy to add many event handlers to one element. It facilitates the addition of event handlers of the same kind to a single element.

JavaScript provides an event handler in the form of the addEventListener() method. This handler can be attached to a specific HTML element you wish to monitor events for, and the element can have more than one handler attached.

addEventListener() Syntax

Here’s the syntax:

target.addEventListener(event, function, useCapture)

addEventListener has three parameters. event and function are most frequently used. useCapture is used occasionally. 

Here’s what all that syntax means:

  • target is the most important parameter; it specifies the DOM object you wish to attach an event listener to. HTML elements are frequently targeted DOM objects.
  • event is a necessary parameter. It’s a string that provides the event’s name. The first thing to remember is that the parameter value does not include the prefix “on.”

    For instance, use “change” rather than “onchange.” Some DOM events areclickchangedragcopy, etc.
  • function specifies the function to run when the event is detected. This is the magic that can allow your web pages to change dynamically.

    Want to learn more about how JavaScript functions work under the hood? Read our guide here: Functions In JavaScript – Simple and Clear Explanation
  • useCapture it is an optional Boolean value (true or false) that specifies whether the event should be executed in the capturing or bubbling phase.

So, addEventListener executes in two phases—capturing or bubbling—and useCapture sets the propagation phase.

To better understand useCapture, let’s take a closer look at bubbling and capturing. 

What are bubbling and capturing?

We can better explain this by looking at a parent element and its child—for example, a div and a button inside it. 

Suppose we applied a click event on both elements using addEventListener method. Which element event gets handled first when a user clicks the button? Well, it depends on the propagation phase. 

  • Bubbling is an inside-out execution phase. That means that execution starts from the inner element and then will move to the outermost element’s event.

    Therefore, the button‘s event will be handled first, followed by the div element’s event.
  • Capturing is the opposite of bubblingIt starts the execution from the outside

    In this case, when you click the button, capturing makes the event listener handle the div element’s event first, then handles the innermost element’s event.

Do you want your event in a bubbling phase? Set the bubbling to false, which is the default value. Conversely, set the value to true to specify the capturing phase. 

addEventListener() method code example

Now that you understand addEventListener and its syntax, let’s see it in action with a code example.

Let’s say you want to give users the ability to hide paragraph text on a webpage by clicking a button. Here’s the initial HTML to build that:

<!doctype html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>addEventListener Example -1</title>
</head>

<body>
	<button id="btn">Click me</button>
	<p id="myText">Can you read me? Click the above button to hide
</body>

</html>

Now we need to access elements on the HTML file and assign a handler that listens for a click event. This handler will hide the paragraph when you click the button. Here’s the JavaScript to accomplish that:

let myBtn = document.getElementById('btn');
let msg = document.getElementById('myText');

myBtn.addEventListener('click', () => {
	msg.style.display = 'none';
})

Output:

See the Pen addEventListener Example -1 by Sunil Pradhan (@Sunil_Pradhan) on CodePen.

Here’s what’s happening:

You will see two elements in the HTML file, each with an ID. This enables them to be accessed by our JavaScript snippet.

In the JavaScript file, you first create a variable myBtn. After that, you access the button element in the HTML with its ID. Eventually, you assign it to the variable you created. 

You then repeat the same action–assign the p element to a variable, then name the variable. 

Eventually, use addEventListener. Your target element is the button at this point, and the event is clickThen, you create a functionThis function adds display: none to the p element. useCapture is false, the default value. 

To summarize, we can hide the paragraph by simply clicking on the button.

How to remove the handler

To remove a handler, we will utilize JavaScript’s removeEventListener:

Syntax:

target.removeEventListener(event, function, useCapture)

removeEventListener has the same parameters as addEventListener, which makes it easy to implement when needed. 

To use event listeners, we use addEventListener() function (to add event), and removeEventListener() function (to remove an event).

To remove the event on the button element in the previous example, we can write the code as shown below:

let myBtn = document.getElementById('btn');
let msg = document.getElementById('myText');

myBtn.removeEventListener('click', () => {
	msg.style.display = 'none';
})

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.

<!doctype html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>addEventListener Example -2</title>
</head>

<body>
	<button id="click-here">Click Here</button>
	<p id="text-to-show"></p>
</body>

</html>
const function1 = () => {
	document.getElementById("text-to-show").innerText = "Hello World";
};
const function2 = () => {
	document.getElementById("text-to-show").innerText = "Hello World again";
};
const function3 = () => {
	document.getElementById("text-to-show").innerText =
		"Hello World once again";
};

document.getElementById("click-here").addEventListener("click", function1);
document.getElementById("click-here").addEventListener("mouseover", function2);
document.getElementById("click-here").addEventListener("mouseout", function3);

Output:

See the Pen addEventListener Example -2 by Sunil Pradhan (@Sunil_Pradhan) on CodePen.

So here we have two HTML elements, a button, and a paragraph by 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”.

Passing parameters to a function when an event occurs

We can not only execute simple functions when an event has occurred, infact we can also pass parameters to a function and then can do some complex calculation as well in response for that event’s occurrence.

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 button is clicked.

See the Pen addEventListener Example -3 by Sunil Pradhan (@Sunil_Pradhan) on CodePen.

Advantage of using Event Listeners

  • Can add multiple functions on same event.
  • Event can be removed using removeEventListener function.
  • Event Propagation can be changed.
  • Can use custom events, like touch events.

Further Reading

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.