JavaScript addEventListener() Practical Examples


Written By - Olorunfemi Akinlua
Advertisement

Introduction

As 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.

To add events within JavaScript to a webpage, we will need the addeventlistener method, which allows us to attach a function that will perform certain actions upon interaction.

In this article, we will discuss how to use the addeventlistener method in JavaScript.

 

Syntax of using the addEventListener method

JavaScript's addEventListener method allows you to attach an event handler to a specific element on a web page. This method is typically used to add interactivity to a webpage by responding to user actions such as clicks, mouse movements, and key presses.

The basic syntax for the addEventListener method is as follows:

element.addEventListener(event, function, useCapture);

Here,

  • element is the DOM element that you want to attach the event to.
  • event is a string that specifies the type of event, such as "click", "mouseover", "keydown", etc.
  • function is the callback function that will be executed when the event occurs.
  • useCapture (optional) is a Boolean value that specifies whether the event should be handled in the capturing phase (true) or the bubbling phase (false). The default value is false.

For example, you can use addEventListener to attach a click event to a button element

let button = document.getElementById("myButton");
button.addEventListener("click", function () {
    alert("Button was clicked!");
});

In this example, the addEventListener method is used to attach a click event to the button element with the id myButton. When the button is clicked, the event handler function will be called and an alert message will be displayed.

Advertisement

 

Practical Examples of JavaScript addeventlistener

Example-1: Attach multiple event handlers to single element

One important thing to keep in mind is that the addEventListener method allows you to attach multiple event handlers to a single element, so you can add multiple event handlers to a button element, for example.

button.addEventListener("click", function () {
    alert("Button was clicked!");
});

button.addEventListener("click", function () {
    console.log("Button was clicked!");
});

In this example, two event handlers are attached to the button element, one that displays an alert message and another that logs a message to the console.

Let’s illustrate this more clearly with a simple HTML page with a button as below

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h1>JavaScript addEventListener</h1>
        <p>
            With the use of the <b>addEventListener</b> method, we can apply
            event handlers (functions) to a specific element.
        </p>
        <button id="myButton">Click Here to Alert Me</button>
    </body>
    <script>
        let button = document.getElementById("myButton");
        button.addEventListener("click", function () {
            alert("You have been alerted");
        });
    </script>
</html>

Output

simple HTML page with a button

 

Example-2: Adding a hover event to a div element

We can try another example where we change the color of a div element when hovered on. Here, we will make use of the mouseover event type, and make use of the style.backgroundColor statement to change the background color of the div element. Also, unlike the last code snippet, we will make use of the querySelector() method to select the hover class.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            div {
                width: 50px;
                height: 75px;
                background-color: blueviolet;
                color: bisque;
                padding: 5%;
            }
        </style>
    </head>
    <body>
        <h1>JavaScript addEventListener</h1>
        <p>
            With the use of the <b>addEventListener</b> method, we can apply
            event handlers (functions) to a specific element.
        </p>
        <div class="hover">
            <p>Hover Me</p>
        </div>
    </body>
    <script>
        let box = document.querySelector(".hover");
        box.addEventListener("mouseover", function () {
            box.style.backgroundColor = "#FF00FF";
        });
    </script>
</html>

Output (before hover/mouseover)

Output (before hover/mouseover)

After mouseover, the background color changes

JavaScript addEventListener() Practical Examples

Another useful feature of the addEventListener method is the ability to specify the event's propagation mode. By default, events propagate from the element where they originated to its parent elements in a process called bubbling. This can be changed by setting the useCapture parameter to true when calling the addEventListener method.

element.addEventListener(eventType, eventHandler, useCapture);

When useCapture is set to true, the event handler will be called during the capture phase, which starts at the outermost element and propagates inward. When useCapture is set to false (the default), the event handler will be called during the bubbling phase, which starts at the innermost element and propagates outward.

 

Example-3: Adding a keydown event to an input field

In this example, when the user presses the Enter key while the input field with id "myInput" has focus, an alert message is displayed.

<!DOCTYPE html>
<html>
  <head>
    <title>Keydown Event Example</title>
  </head>
  <body>
    <form>
      <input type="text" id="myInput" placeholder="Enter your name">
    </form>
    <script>
      var input = document.getElementById("myInput");
      input.addEventListener("keydown", function(event){
        if(event.keyCode === 13){
          alert("Enter key was pressed!");
        }
      });
    </script>
  </body>
</html>

Output

JavaScript addEventListener() Practical Examples

 

Example-4: Add a change event to a select element to show the selected value

In this example, when the user changes the selected option in the select element with id "mySelect", a paragraph element with id "selectedValue" will be updated to show the selected value. The this.value property returns the value of the selected option.

<!DOCTYPE html>
<html>
  <head>
    <title>Select Change Event Example</title>
  </head>
  <body>
    <select id="mySelect">
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>

    <p id="selectedValue"></p>

    <script>
      var select = document.getElementById("mySelect");
      select.addEventListener("change", function(){
        var selectedValue = document.getElementById("selectedValue");
        selectedValue.innerHTML = "Selected value: " + this.value;
      });
    </script>
  </body>
</html>

Output:

JavaScript addEventListener() Practical Examples

 

Example-5: Adding a submit event to a form to validate input fields

In this example, three buttons are created with ids "myButton1", "myButton2" and "myButton3" respectively and also a div with id "output" . When any of the buttons are clicked, the corresponding text is displayed in the output div element. The innerHTML property is used to change the text inside the output div element. In the script, we first get the buttons and output div element by their ids. Then we add a click event listener to each button, and inside the event listener function, we update the text inside the output div element to indicate which button was clicked.

<!DOCTYPE html>
<html>
  <head>
    <title>Multiple Event Listeners Example</title>
  </head>
  <body>
    <button id="myButton1">Button 1</button>
    <button id="myButton2">Button 2</button>
    <button id="myButton3">Button 3</button>
    <div id="output"></div>

    <script>
      // Get the buttons by id
      var button1 = document.getElementById("myButton1");
      var button2 = document.getElementById("myButton2");
      var button3 = document.getElementById("myButton3");
      var output = document.getElementById("output");

      // Add click event listener to all buttons
      button1.addEventListener("click", function(){
        output.innerHTML = "Button 1 was clicked!";
      });
      button2.addEventListener("click", function(){
        output.innerHTML = "Button 2 was clicked!";
      });
      button3.addEventListener("click", function(){
        output.innerHTML = "Button 3 was clicked!";
      });
    </script>
  </body>
</html>

Output:

JavaScript addEventListener() Practical Examples

 

 

Summary

The addEventListener method in JavaScript is used to attach an event handler to an element. It allows you to specify a function that will be executed when a specific event occurs on the element. It allows you to attach event handlers to specific elements, listen for a wide range of events, and control the way events propagate through the document. Understanding how to use addEventListener is an important part of being proficient in JavaScript and web development.

 

References

EventTarget.addEventListener() - Web APIs | MDN (mozilla.org)
Element: click event - Web APIs | MDN (mozilla.org)
Event - Web APIs | MDN (mozilla.org)

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment