Dom Events in JavaScript
? DOM Events in JavaScript
What are DOM Events?
DOM Events are actions or occurrences that happen in the browser, which JavaScript can respond to.
Examples: user clicks a button, moves the mouse, presses a key, submits a form, loads the page, etc.
Event Types
| Event Type | Description | Example |
|---|---|---|
| Mouse Events | click, dblclick, mouseover, mouseout, mousedown, mouseup | Detect mouse actions |
| Keyboard Events | keydown, keyup, keypress | Detect key presses |
| Form Events | submit, change, input, focus, blur | Form-related user interactions |
| Window Events | load, resize, scroll, unload | Events on the browser window |
| Touch Events | touchstart, touchmove, touchend | For touch devices |
How to Handle Events
1. Using HTML Attribute (not recommended)
<button onclick="alert('Clicked!')">Click Me</button>2. Using DOM Element Properties
const btn = document.getElementById("btn");btn.onclick = function() { alert("Clicked!");};3. Using addEventListener (recommended)
btn.addEventListener("click", () => { alert("Clicked!");});Event Object
When an event happens, the browser passes an event object to the event handler, which contains details like:
event.target— the element that triggered the eventevent.type— the event type (click,keydown, etc.)event.preventDefault()— stops the default browser behavior (e.g., form submission)event.stopPropagation()— stops the event from bubbling up
Example: Prevent Form Submission
<form id="myForm"> <input type="text" name="name" /> <button type="submit">Submit</button></form><script>const form = document.getElementById("myForm");form.addEventListener("submit", (event) => { event.preventDefault(); // stop form from submitting alert("Form submission prevented!");});</script>Event Bubbling and Capturing
Bubbling: Event starts from the target element and bubbles up to parent elements.
Capturing: Event travels from the root down to the target element.
By default, event listeners listen during bubbling phase.
element.addEventListener("click", handler, true); // true = capturing phaseEvent Delegation
Attach a single event listener on a parent element to handle events on its children — efficient for dynamic elements.
document.getElementById("parent").addEventListener("click", (event) => { if (event.target.matches(".child")) { console.log("Child clicked:", event.target); }});Summary
DOM events let JavaScript respond to user interactions.
Use
addEventListenerfor attaching handlers.Event object gives info & control over event behavior.
Event delegation optimizes event handling on many child elements.
Want me to give you examples on event delegation or handling keyboard and mouse events?