Labs ICT
โญ Pro Login

DOM Events

1 min read | JavaScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

addEventListener

Attach event handlers to elements using addEventListener. It supports multiple handlers for the same event.

const btn = document.querySelector("#myButton");

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

btn.addEventListener("click", () => {
  btn.style.backgroundColor = "green";
});

Common Event Types

Mouse, keyboard, form, focus, and window events. Each type provides specific properties on the event object.

const input = document.querySelector("#nameInput");
const box = document.querySelector("#hoverBox");

input.addEventListener("keyup", (e) => {
  console.log("Key:", e.key, "Value:", input.value);
});

box.addEventListener("mouseenter", () => {
  box.style.opacity = "0.5";
});

box.addEventListener("mouseleave", () => {
  box.style.opacity = "1";
});

The Event Object

The event object is automatically passed to handlers. It contains properties like target, type, clientX, and methods like preventDefault().

const link = document.querySelector("a");

link.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("Link was clicked");
  console.log("Target:", event.target.tagName);
  console.log("Mouse X:", event.clientX);
});

๐Ÿงช Quick Quiz

How do you add a click event to a button element?