---
title: "AddEventListener JavaScript: What It Is and How To Use It | CoderPad"
description: "Event listeners are essential in web development as they help in returning proper responses triggered by an event. AddEventListener is a fundamental method in JavaScript -- here's everything you need to know about it."
canonical: "https://coderpad.io/blog/development/addeventlistener-javascript/"
last_modified: "2023-06-05 14:11:59"
---
[Back to blog](https://coderpad.io/blog/)

# AddEventListener JavaScript: What It Is and How To Use It

September 6, 2022 5 Minute Read

By Akande Olalekan Toheeb

[Development](https://coderpad.io/blog/development/)

JavaScript event listeners (or event handlers) are essential in web development. Why? Events constantly occur on your website, and they often change the interface.

Event handlers provide a built-in solution for configuring activities anytime your page changes.

In this post, you’ll learn about`addEventListener`, a particular event handler in JavaScript. We’ll cover its definition, syntax, and code example. In the end, you’ll learn how to remove the handler using`removeEventlistener`and some other concepts.

Let’s get to it.

## What is addEventListener in JavaScript?

When a user or browser interacts with a webpage, an event occurs. Event handlers are used to create a customized piece of code that will run in response to specific events (e.g., opening a pop-up window when a user clicks a button). Some events are user-generated, while some are generated by APIs.

JavaScript includes a built-in method called`addEventListener.`It’s a [DOM Level 2](https://en.wikipedia.org/wiki/DOM_events#DOM_Level_2) event handler. You can use it to attach an event handler to a specific element. It in no way replaces the existing event handlers.

`addEventListener`makes adding many event handlers to one element easy — it lets you respond to events associated with an element via an event handler function. The`change`effect is an example of an event. You can attach an event handler to any DOM object.

## AddEventListener syntax in JavaScript

Let’s take a look at 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 are`click`,`change`,`drag`,`copy`, etc.
- `function`is a piece of code that triggers when the event fires. It makes the web pages dynamic and is an essential part of the method. Want to learn more about how JavaScript functions work under the hood? Read our guide [here](https://coderpad.io/blog/development/what-you-never-learned-about-javascript-functions/).
- `useCapture`is an optional parameter. It’s a Boolean data type with either true or false values.`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 I applied a`click`event on both elements using`addEventListener`. 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 bubbling. It 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 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:

```
<html>
	<head>
		<meta charset="UTF-8">
		<title>addEventListener() Code Example</title>
		<link rel="stylesheet" href="index.css">
		<script src="index.js"/>
	</head>
	<body>
		<button id="btn">Click me</button>
		<p id="myText">Can you read me? Click the above button to hide me</p>
	</body>
</html>Code language: HTML, XML (xml)
```

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';
})
Code language: JavaScript (javascript)
```

Here’s what’s happening:

You’ll 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`click`. Then, you create a function. This function adds`display: none`to the`p`element.`useCapture`is`false`, the default value.

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

## How to remove the handler

To remove a handler, you’ll utilize JavaScript’s`removeEventListener`:

`target.removeEventListener(event, function, useCapture)`

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

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

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

myBtn.removeEventListener('click', ()=>{
  msg.style.display='none';
})
Code language: JavaScript (javascript)
```

## How to stop event propagation

You may need to stop the propagation of an event because you only want it to affect a limited element.

Let’s take a`div`and a`p`inside the div as a use case. You want to stop the event from getting to the`p`element.

```
<div>
     <p>I am a paragraph</p>
</div>
Code language: HTML, XML (xml)
```

The first thing to remember is that you can use`useCapture`to catch an event on the parent element before it gets to the children and stop it.

To do this, you’ll need to set`useCapture`to`true`and use the`stopPropagation`function on the event object, like so:

```
div.addEventListener("click", myFunc => {
  console.log("The child Event won't execute")
  myFunc.stopPropagation()
}, { capture: true })

p.addEventListener("click", () => {
  console.log("You can't find me on the console")
})
Code language: JavaScript (javascript)
```

When you run the code above, you’ll see`"The child Event won't execute"`logged to the console and nothing else. This happens because we stopped the event propagation on the parent using`stopPropagation`.

## Is it better to use addEventListener or onClick?

`onClick`is an example of an HTML event handler attribute. It’s also used to handle events. Meanwhile,`addEventListener`is the recommended way to assign event handlers.

### Why?

`addEventListener`gives you control over the execution phase. Bubbling and capturing are not easy to handle with`onClick`.

Additionally,`addEventListener`allows the addition of multiple events to an element. It also allows the addition of multiple handlers to an event. It works well with libraries and JavaScript modules.

## Before parting ways

`addEventListener`is an easy way to handle events on your websites. You can add multiple events to a particular element. You can remove events and even set the propagation phase. This is a superpower that enhances writing clean code.

Play around with the code you learned today in the sandbox below:

This post was written by Akande Olalekan Toheeb. [Akande](https://www.linkedin.com/in/akande-olalekan-toheeb-2a69a0221/) is a front-end developer and technical writer who loves teaching, learning, and building web tools and applications. He has experience with HTML, CSS, BOOTSTRAP, TAILWIND, LESS, SASS, GIT, NODEJS, and JAVASCRIPT and has built projects with other frameworks too.

## Subscribe for more CoderPad insights

## Trending Articles

Previous slide Next slide [Development

## What is Prompt Engineering?

Introducing AI tools such as ChatGPT and Bard helps increase the efficiency of tasks such as data generation, code generation and completion, text summarization, etc. How were these AI tools trained to answer almost every question you ask them? The answer, prompt engineering, is discussed in this blog post.

Read the post](https://coderpad.io/blog/development/what-is-prompt-engineering/) [Development

## A Guide To Using React’s useCallback() Hook

Are you looking to optimize your React applications? Have you heard of the useCallback hook? useCallback is a powerful React hook that helps you optimize your application by preventing unnecessary re-renders. In this post, we'll dive into React's useCallback() hook, define referential equality and callback functions and how to tie it all together.

Read the post](https://coderpad.io/blog/development/a-guide-to-using-reacts-usecallback-hook/) [Development

## MySQL vs. PostgreSQL: How Do They Compare?

A database is a convenient tool that allows users to access information, maintain records, and apply commonly used operations, such as insertion, modification, deletion, and data organization. Learn about MySQL vs PostgreSQL, their features, advantages, and disadvantages. Finally, check out which one is the best choice for you.

Read the post](https://coderpad.io/blog/development/mysql-vs-postgresql-how-do-they-compare/) [Development

## PostgreSQL LIKE Operator: A Detailed Guide

When using databases, searching for values that match a given pattern is a familiar necessity. Learn how you can retrieve entries with queries including a particular string using Postgres LIKE operator.

Read the post](https://coderpad.io/blog/development/postgresql-like-operator-a-detailed-guide/) [Development

## How To Use DataProvider In TestNG With Examples

When it comes to testing there are many tools and techniques available. In this post, we'll discuss how to use DataProvider with TestNG.

Read the post](https://coderpad.io/blog/development/how-to-use-dataprovider-in-testng-with-examples/) [Development

## How To Get Up And Running With Django Migrations: A Guide

Django migrations are a way of handling the application of changes to a database schema. By following the steps outlined in this guide, you can easily set up and use migrations in your Django projects.

Read the post](https://coderpad.io/blog/development/how-to-get-up-and-running-with-django-migrations-a-guide/) [Development

## Writing A Parameterized Test In JUnit With Examples

A JUnit parameterized test allows you to decouple data from structure, generating cleaner and more reliable tests. Learn more in this guide.

Read the post](https://coderpad.io/blog/development/writing-a-parameterized-test-in-junit-with-examples/) [Development

## How To Use Assert In JUnit With Examples

The JUnit Assert class is what you use to write unit testing assertions in JUnit. Learn more about it in this guide, full of examples.

Read the post](https://coderpad.io/blog/development/how-to-use-assert-in-junit-with-examples/) [Development

## A Simple Guide To TypeORM: What It Is And How To Use It

Considering current languages have object-oriented programming features, most database management systems are based on the relational model, with tables instead of objects. For these reasons, mapping relational objects is very important in development. In this article, you will learn what TypeORM, one of the main tools used today, is.

Read the post](https://coderpad.io/blog/development/a-simple-guide-to-typeorm-what-it-is-and-how-to-use-it/) [Development

## Using PreparedStatement in JDBC With Examples

In this post, we'll see why and how to work with JDBC and PreparedStatement. We will also learn along with examples using code.

Read the post](https://coderpad.io/blog/development/using-preparedstatement-in-jdbc-with-examples/) [Development

## React vs React Native: The Differences Explained

React and React Native are similar in that they both allow web developers to build applications based on the unique concept of components. But the two frameworks do this in radically different ways. In this post, we cover the key differences between react and react native frameworks, implementation, and which is an appropriate choice.

Read the post](https://coderpad.io/blog/development/react-vs-react-native-the-differences-explained/) [Development

## Logging in Django

The most challenging part of fixing a problem is identifying it. Unfortunately, this statement is exceptionally true when it comes to debugging. Learn how to use the power of logging into your Django applications to improve your debug process in this article.

Read the post](https://coderpad.io/blog/development/logging-in-django/)

## Hire with confidence.

See why engineering teams trust CoderPad to evaluate developers with realistic, AI-ready hiring workflows.

[Request a demo](https://coderpad.io/sales/)
