Understanding the Event Object
Every event handler function receives an event object as a parameter, which holds detailed information about the triggered eventβlike mouse position, key pressed, or target element.
π¦ Example: Accessing the Event Object
document.addEventListener("click", function(event) {
console.log(event); // Logs the entire event object
});
π― Common Event Object Properties
event.typeβ the type of event (e.g., "click", "keydown")event.targetβ the element that triggered the eventevent.currentTargetβ the element the event listener is attached toevent.clientX / clientYβ mouse position on the screenevent.keyβ the key pressed (for keyboard events)event.preventDefault()β prevents default behaviorevent.stopPropagation()β stops event from bubbling up
π Example: Using `event.target`
document.querySelector("ul").addEventListener("click", function(e) {
console.log("You clicked on:", e.target.tagName);
});
π« Preventing Default Action
Used to stop things like form submission, link redirection, etc.
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault(); // Stops form from submitting
alert("Form intercepted!");
});
π§ Stopping Propagation
Use this when you donβt want an event to bubble up to parent elements.
button.addEventListener("click", function(e) {
e.stopPropagation();
console.log("Button clicked without bubbling up");
});
π‘ Tip: Always use the
event object to get dynamic and context-aware responses from your JavaScript code.