Introduction to Events
In JavaScript, events are actions or occurrences that happen in the browser or on the user interface, such as clicking a button, typing in a text field, or resizing the window. Events allow JavaScript to respond to user interactions, making web pages dynamic and interactive.
Event Types
Events can be broadly categorized based on their origin:
- User Interface (UI) Events:
load
,resize
,scroll
- Mouse Events:
click
,dblclick
,mouseover
,mouseout
,mousemove
- Keyboard Events:
keydown
,keyup
,keypress
- Form Events:
submit
,change
,input
,focus
,blur
- Clipboard Events:
copy
,cut
,paste
- Drag & Drop Events:
dragstart
,dragover
,drop
- Custom Events: User-defined events to trigger specific logic
Event Handling
Event handling allows JavaScript to respond to events.
Methods to handle events:
- Inline HTML:
<button onclick="doSomething()">Click</button>
- DOM Property:
element.onclick = function() { ... }
- addEventListener (Preferred):
const btn = document.getElementById("myButton");
btn.addEventListener("click", () => {
console.log("Button clicked!");
});
Event Object:
When an event occurs, an event object is passed to the handler containing information like:
event.type
– type of eventevent.target
– element that triggered the eventevent.preventDefault()
– prevent default browser behaviorevent.stopPropagation()
– stop the event from bubbling
Event Propagation
Event propagation defines how events travel through the DOM. There are three phases:
- Capturing Phase: Event travels from the root down to the target element.
- Target Phase: Event reaches the target element.
- Bubbling Phase: Event bubbles up from the target back to the root.
element.addEventListener("click", handler, true); // true → capturing
element.addEventListener("click", handler, false); // false → bubbling (default)
Methods to control propagation:
event.stopPropagation()
– stops further propagationevent.stopImmediatePropagation()
– stops other listeners on the same element
Event Handling Patterns
Some common patterns for event handling:
- Direct Event Binding: Attach handler to each element individually
- Event Delegation: Attach a single handler to a parent element to manage events of its children
document.getElementById("parent").addEventListener("click", (event) => {
if (event.target.tagName === "BUTTON") {
console.log("Button inside parent clicked");
}
});
One-time Event Listeners: Execute handler only once
element.addEventListener("click", handler, { once: true });
Prevent Default Behavior: For forms, links, or custom actions
form.addEventListener("submit", (e) => e.preventDefault());