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";
});
Try it Yourself โ
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";
});
Try it Yourself โ
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);
});
Try it Yourself โ