How to Use Event Listeners in JavaScript

Many web applications rely on some form of event to carry out their functions. At some point, a human interacts with their interface, which generates an event. These human-driven events typically rely on a peripheral device, such as a mouse or keyboard.

When a device creates an event, the program can listen for it, to know when to carry out specific behavior. In this tutorial, you’ll learn how to listen for events using JavaScript.

What Is Event-Driven Programming?

Event-driven programming is the name of a paradigm that relies on the execution of an event to perform its functions. It’s possible to create an event-driven program in any high-level programming language. But event-driven programming is most common in languages like JavaScript that integrate with a user interface.

What Is an Event Listener?

An event listener is a function that initiates a predefined process if a specific event occurs. So, an event listener “listens” for an action, then calls a function that performs a related task. This event can take one of many forms. Common examples include mouse events, keyboard events, and window events.

Creating an Event Listener Using JavaScript

You can listen for events on any element in the DOM. JavaScript has an addEventListener() function that you can call on any element on a web page. The addEventListener() function is a method of the EventTarget interface. All objects that support events implement this interface. This includes the window, the document, and individual elements on the page.

The addEventListener() function has the following basic structure:

element.addEventListener("event", functionToExecute);

Where:

  • the element can represent any HTML tag (from a button to a paragraph)
  • the “event” is a string naming a specific, recognized action
  • the functionToExecute is a reference to an existing function

Let’s create the following web page that has a few HTML elements:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
</head>
<body>
 <div id="home">
 <h1 class="mainHeading">Welcome</h1>
 <p>
 Hello, welcome to my website.
 </p>
 <button class="btn" id="btn=1">Learn More</button>
 </div>
 <div id="about">
 <h2 class=subheading>User Info</h2>
 <label for="username">User Name: </label>
 <input type="text" id="username">
 <button class="btn" id="btn-2">Submit</button>
 </div>
 <script src="app.js"></script>
</body>
</html>

The HTML code above creates a simple page that links to a JavaScript file called app.js. The app.js file will contain the code to set up the event listeners. So, if you want to initiate a specific process whenever a user clicks the first button on the web page, this is the file to create it in.

The app.js File

document.querySelector('.btn').addEventListener("click", clickDemo)
function clickDemo(){
 console.log("Hi there")
}

The JavaScript code above accesses the first button on the page using the querySelector() function. It then adds an event listener to this element using the addEventListener() method. The specific event it listens for has the name “click”. When the button fires that event, the listener will call the clickDemo() function.

 

The clickDemo() function prints “Hi there” to the browser console. Every time you click the button, you should see this output in your console.

The “click” Event Output

Click event output

What Are Mouse Events?

JavaScript has a MouseEvent interface that represents events that occur because of a user’s interaction with their mouse. Several events use the MouseEvent interface. These events include the following:

  • click
  • dblclick
  • mousemove
  • mouseover
  • mouseout
  • mouseup
  • mousedown

The click event occurs when a user presses and releases a mouse button while its pointer is over an element. This is exactly what occurred in the previous example. As you can see from the list above, mouse events can take many forms.

Another common mouse event is dblclick, which stands for double-click. This fires when a user clicks a mouse button twice in quick succession. A remarkable thing about the addEventListener() function is that you can use it to assign multiple event listeners to a single element.

Adding a dblclick Event to the First Button

document.querySelector('.btn').addEventListener("dblclick", dblclickDemo)
function dblclickDemo(){
 alert("This is a demonstration of how to create a double-click event")
}

Adding the code above to the app.js file will effectively create a second event listener for the first button on the web page. So, clicking the first button twice will create the following alert in the browser:

dblclick event output

In the image above you’ll see the alert that’s generated, and you’ll also see that two more “Hi there” outputs are in the console. This is because a double-click event is a combination of two click events and there are event listeners for both the click and the dblclick events.

The names of the other mouse events in the list describe their behavior. The mousemove event occurs every time a user moves their mouse when the cursor is over an element. The mouseup event occurs when a user holds down a button over an element, then releases it.

What Are Keyboard Events?

JavaScript has a KeyboardEvent interface. This listens for interactions between a user and their keyboard. In the past, KeyboardEvent had three event types. However, JavaScript has since deprecated the keypress event.

So, the keyup and keydown events are the only two recommended keyboard events, which are all you need. The keydown event occurs when a user presses down on a key, and the keyup event occurs when a user releases it.

Revisiting the HTML example above, the best place to add a keyboard event listener is on the input element.

Adding a Keyboard Event Listener to the app.js File

let greetings = document.querySelector('p');
document.querySelector('input').addEventListener("keyup", captureInput)
function captureInput(e){
 greetings.innerText = (`Hello ${e.target.value}, welcome to my website.`)
}

The code above uses the querySelector() function to access the paragraph and input elements on the page. It then calls the addEventListener() method on the input element, which listens for the keyup event. Whenever a keyup event occurs, the captureInput() function takes the key value and adds it to the paragraph on the page. The e parameter represents the event, which JavaScript assigns automatically. This event object has a property, target, which is a reference to the element the user interacted with.

In this example, the label attached to the input field requests a username. If you type your name into the input field, then the web page will look something like this:

Keyup event output

The paragraph now contains the input value which, in the example above, is “Jane Doe”.

addEventListener Captures All Sorts of User Interaction

This article introduced you to the addEventListener() method, as well as several mouse and keyboard events you can use with it. At this point, you know how to listen for a particular event, and how to create a function that responds to it.

The addEventListener provides extra capability, however, via its third parameter. You can use it to control event propagation: the order in which events move from elements to their parents or children.

Releated

Learn How to Use DOM Selectors

The Document Object Model (DOM) is the structural representation of an HTML document. The DOM is a tree of nodes that the browser creates for each webpage on the internet. The DOM is object-oriented. Each element in the DOM has its own set of attributes and methods that you can access using JavaScript. In this […]

The 8 Best Features of the Anima App All Designers Should Use

A unified design-to-code platform like Anima can help you speed up website and app development projects. Anima is a design-to-code plug-in for Figma, Adobe XD, and Sketch. It enables designers to create high-fidelity prototypes for mobile apps, landing pages, or websites, and developers can easily get responsive, clean, and reusable codes that are also production-ready. […]