J

JavaScript Handbook

Clean • Professional

DOM Event Listener in JavaScript

2 minute

DOM Event Listener

The addEventListener() method in JavaScript is a core feature of the HTML DOM that allows developers to attach event handlers to HTML elements. It makes web pages interactive, enabling dynamic responses to user actions (clicks, typing, hovering) and browser events (page load, scroll, resize).

Syntax:

element.addEventListener(event, handler, options);
  • event — Name of the event (e.g., "click", "input", "submit").
  • handler — Function executed when the event occurs. Receives an event object.
  • options (optional) — Object controlling event behavior:
    • capture: true → Use capturing phase.
    • once: true → Listener runs once and removes itself automatically.
    • passive: true → Improves performance for scroll/touch events by preventing preventDefault().

Basic Example:

<button id="myButton">Click Me</button>
<script>
  const button = document.getElementById("myButton");

  button.addEventListener("click", () => {
    alert("Button clicked!");
  });
</script>

Advantages of addEventListener()

  • Attach multiple listeners to the same element/event.
  • Control event phases (bubbling vs capturing).
  • Keep JavaScript logic separate from HTML (better for maintainability).
  • Modern, recommended over inline event attributes (e.g., onclick) or DOM properties.

Event Object

The event object provides details about the triggered event.

button.addEventListener("click", (event) => {
  console.log("Event type:", event.type);         // click
  console.log("Clicked element:", event.target);  // button element
  event.preventDefault(); // Prevent default action
  event.stopPropagation(); // Stop bubbling/capturing
});

Common Properties & Methods:

Property / MethodDescription
event.targetElement that triggered the event
event.typeType of event (click, input, etc.)
event.preventDefault()Prevents default browser action
event.stopPropagation()Stops event from bubbling/capturing

Common Event Types

  • Mouse Events: click, dblclick, mouseover, mouseout, mousemove, mousedown, mouseup
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, input, change, focus, blur, reset
  • Window/Document Events: load, resize, scroll, unload
  • Clipboard Events: copy, paste, cut
  • Drag & Drop: drag, drop, dragstart, dragover, dragenter, dragleave, dragend
  • Touch & Pointer Events: touchstart, touchmove, touchend, pointerdown, pointerup, pointermove

Practical Examples

Multiple Events on One Element

const input = document.querySelector("input");

input.addEventListener("focus", () => input.style.border = "2px solid blue");
input.addEventListener("blur", () => input.style.border = "1px solid gray");
input.addEventListener("input", (e) => console.log("Typing:", e.target.value));

Form Handling & Validation

<form id="myForm">
  <input id="username" type="text" placeholder="Enter username">
  <button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("myForm");
const input = document.getElementById("username");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  if(input.value.length < 3) {
    input.classList.add("error");
    console.log("Username too short!");
  } else {
    input.classList.remove("error");
    console.log("Form submitted:", input.value);
  }
});

input.addEventListener("input", (event) => {
  if(event.target.value.length >= 3) {
    input.classList.add("valid");
    input.classList.remove("error");
  } else {
    input.classList.remove("valid");
    input.classList.add("error");
  }
}, { passive: true });
</script>

Event Delegation

const list = document.getElementById("list");
list.addEventListener("click", (event) => {
  if(event.target.tagName === "LI") {
    console.log("Clicked:", event.target.textContent);
  }
});

Removing Event Listeners

In JavaScript, addEventListener lets elements respond to user actions like clicks or typing. removeEventListener is used to stop these responses, prevent memory leaks, or control dynamic behavior.

function handleClick() { console.log("Clicked!"); }

button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick); // Works only with named/stored functions

 

Article 0 of 0