Adding and Removing Event Listeners

Introduction

Event listeners are essential for creating interactive and dynamic web applications. In this guide, you’ll learn how to:

What Are Event Listeners?

An event listener "listens" for specific events, such as a user clicking a button, and executes a callback function when that event occurs. Event listeners are added using the addEventListener method and removed with the removeEventListener method.

Syntax


Element.addEventListener(eventType, callbackFunction);
Element.removeEventListener(eventType, callbackFunction);
            

Examples of Event Handling

1. Handling a Button Click Event

Let’s create an event listener that increments a counter each time a button is clicked.


HTML:
<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>
  <body>
    <button id="increment-count">I have been clicked <span id="clicked-count">0</span> times</button>
  </body>
</html>

JavaScript (script.js):
window.addEventListener("DOMContentLoaded", () => {
  const button = document.getElementById("increment-count");
  const count = document.getElementById("clicked-count");
  let clicks = 0;
  button.addEventListener("click", () => {
    clicks += 1;
    count.innerHTML = clicks;
  });
});
            

2. Handling a Checkbox Check Event

Display or hide a <div> when a checkbox is checked or unchecked.


HTML:
<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Pizza Toppings</h1>
    <input type="checkbox" id="on-off">
    <label for="on-off">Extra Cheese</label>
    <div id="now-you-see-me" style="display:none">Add $1.00</div>
  </body>
</html>

JavaScript (script.js):
window.addEventListener("DOMContentLoaded", () => {
  const checkbox = document.getElementById("on-off");
  const divShowHide = document.getElementById("now-you-see-me");

  checkbox.addEventListener("click", () => {
    if (checkbox.checked) {
      divShowHide.style.display = "block";
    } else {
      divShowHide.style.display = "none";
    }
  });
});
            

3. Handling User Input

Mirror user input in a <div> as they type.


HTML:
<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>
  <body>
    <input id="original" type="text" placeholder="Type here">
    <div id="mirrored"></div>
  </body>
</html>

JavaScript (script.js):
window.addEventListener("DOMContentLoaded", () => {
  const mirroredDiv = document.getElementById("mirrored");
  const originalText = document.getElementById("original");

  originalText.addEventListener("input", (event) => {
    mirroredDiv.innerText = event.target.value;
  });
});
            

Using CSS for Efficient Event Handling

Instead of setting style.display directly in JavaScript, use CSS classes for better reusability and readability:

CSS:


.show {
  display: block;
}
.hide {
  display: none;
}
            

HTML:


<div id="now-you-see-me" class="hide">Add $1.00</div>
            

JavaScript:


checkbox.addEventListener("click", () => {
  if (checkbox.checked) {
    divShowHide.classList.remove("hide");
    divShowHide.classList.add("show");
  } else {
    divShowHide.classList.remove("show");
    divShowHide.classList.add("hide");
  }
});
            

What You Learned

In this guide, you explored:

These skills are fundamental for creating dynamic and user-friendly web applications.