JavaScript Event Handling: addEventListener, Event Objects & Control

An Event is a signal that something has occurred in the browser—such as a user clicking a button, submitting a form, pressing a keyboard key, resizing the window, or a resource finishing loading. Event Listeners are functions registered to execute whenever that specific event occurs.

The addEventListener Standard

const submitBtn = document.getElementById("submit-btn");

// element.addEventListener(eventType, callbackFunction, options)
submitBtn.addEventListener("click", (event) => {
    console.log("Button clicked!");
    console.log("Event Type:", event.type);       // "click"
    console.log("Event Target:", event.target);   // The clicked <button> element
});

The Event Object (e / event)

When an event fires, the browser automatically passes an Event Object to the handler containing vital details regarding the action:

Property / Method Significance & Practical Use
e.target The exact DOM element that originally triggered the event (the origin element).
e.currentTarget The DOM element to which the event listener is currently attached.
e.preventDefault() Cancels the browser's default behavior (e.g. stops form page-reload).
e.stopPropagation() Prevents the event from bubbling up the DOM tree to ancestor elements.

Common Event Categories & Code Examples

// 1. FORM SUBMIT EVENT (Preventing Page Reload)
const loginForm = document.getElementById("login-form");
loginForm.addEventListener("submit", (e) => {
    e.preventDefault(); // Stop full-page reload!
    console.log("Handling login asynchronously via JavaScript Fetch...");
});

// 2. KEYBOARD EVENT (Listening for Enter Key)
const searchInput = document.getElementById("search-box");
searchInput.addEventListener("keydown", (e) => {
    if (e.key === "Enter") {
        console.log(`Initiating search for query: "${e.target.value}"`);
    }
});

// 3. WINDOW SCROLL & RESIZE
window.addEventListener("scroll", () => {
    console.log("Current Vertical Scroll Position:", window.scrollY);
});

University Exam Corner (BCA Examination Notes)

Exam Question: "How do you remove an event listener in JavaScript?"

Answer: Use element.removeEventListener(eventType, callbackFunction). Crucially, the callback function MUST be a named reference. Anonymous arrow functions cannot be removed because they represent distinct memory references:

function handleClick() { console.log("Clicked"); }

// Register named listener:
btn.addEventListener("click", handleClick);

// Cleanly unbind listener:
btn.removeEventListener("click", handleClick);

Next Step

How do events travel up and down the DOM tree? How can one listener handle 10,000 buttons? Proceed to: JavaScript Event Bubbling, Capturing & Delegation →

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!