🎯 JavaScript DOM Events – Everything You Need to Know
DOM Events are how your JavaScript code responds to user interactions (clicks, scrolls, typing, etc.) or browser actions (loading, resizing, etc.). They’re a core part of making websites interactive.
🧠 What Is a DOM Event?
A DOM event is a signal that something happened in the browser (like a button click or key press), and JavaScript can listen and react to that event.
🔧 Attaching Event Listeners
✅ Basic Syntax
js
element.addEventListener("event", handlerFunction);
✅ Example
js
document.querySelector("#btn").addEventListener("click", () => {
alert("Button clicked!");
});
🎯 Common DOM Events
Type | Event | Description |
---|---|---|
Mouse | click , dblclick , mouseover , mouseout , contextmenu | Interactions with mouse |
Keyboard | keydown , keyup , keypress | Keyboard input |
Form | submit , change , input , focus , blur | Form interactions |
Window | load , resize , scroll , beforeunload | Page/window events |
Clipboard | copy , cut , paste | Clipboard actions |
📦 Event Object (event
)
You can get details about the event using the event object:
js
button.addEventListener("click", function(event) {
console.log(event.target); // the clicked element
console.log(event.type); // "click"
});
🛠️ Example: Prevent Form Submission
js
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevent actual submit
console.log("Form submitted!");
});
⚡ Event Delegation
Instead of attaching events to multiple children, you attach one event to a parent:
js
document.querySelector("#list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
alert("Clicked: " + e.target.textContent);
}
});
✅ This saves memory and works for dynamically added elements.
🧩 Event Propagation
📈 Bubbling (default)
Event goes from target → up to parent
js
// Clicks bubble from <button> → <div> → <body>...
📉 Capturing
Event goes top → down to the target
js
element.addEventListener("click", handler, true); // true = capture phase
🧪 stopPropagation()
and stopImmediatePropagation()
Prevent events from continuing to bubble/capture:
js
element.addEventListener("click", function(e) {
e.stopPropagation();
});
📚 Learn More
✅ Summary
Task | Method |
---|---|
Listen to an event | addEventListener() |
Stop bubbling | event.stopPropagation() |
Cancel default behavior | event.preventDefault() |
Get event info | event.target , event.type |