Clean β’ Professional
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.
load, resize, scrollclick, dblclick, mouseover, mouseout, mousemovekeydown, keyup, keypresssubmit, change, input, focus, blurcopy, cut, pastedragstart, dragover, dropEvent handling allows JavaScript to respond to events.
Methods to handle events:
<button onclick="doSomething()">Click</button>element.onclick = function() { ... }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 bubblingEvent propagation defines how events travel through the DOM. There are three phases:
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 elementSome common patterns for event handling:
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());Β