
JavaScript is an event-driven language, which means almost everything in the browser happens because of an event — a click, a key press, page load, API response, timer, or even a custom action triggered inside a component.
Understanding events deeply is essential for building interactive UIs, especially in Lightning Web Components (LWC), React, and modern frameworks. This guide takes you from beginner concepts to advanced patterns used in real-world applications.
Watch Our Video Tutorial
What Are Events in JavaScript?
An event is an action or occurrence recognized by the browser, such as:
- User actions (click, input, keypress)
- Browser actions (load, scroll, resize)
- Programmatic actions (CustomEvent dispatch)
Events allow JavaScript to “react” to what is happening on the web page.
Why Events Are Important?
- They make web pages interactive
- Help capture user actions
- Drive component communication (like LWC)
- Trigger business logic
- Control UI updates efficiently
Types of Events in JavaScript
1. Mouse Events
- click
- dblclick
- mousedown
- mouseup
- mousemove
- mouseenter / mouseleave
button.addEventListener("click", () => { console.log("Button clicked!"); }); 2. Keyboard Events
- keydown
- keypress
- keyup
document.addEventListener("keydown", (event) => { console.log("Key pressed:", event.key); });
3. Input & Form Events
- input
- change
- submit
- focus / blur
4. Clipboard Events
- copy
- cut
- paste
5. Window Events
- load
- resize
- scroll
- beforeunload
6. Touch Events (Mobile)
- touchstart
- touchmove
- touchend
7. Custom Events
Manually created events using CustomEvent (commonly used in LWC).
The Event Listener
Syntax
element.addEventListener("eventName", callbackFunction);
Example
document.querySelector("#btn").addEventListener("click", handleClick); function handleClick() { console.log("Clicked!"); }
Removing Event Listeners
function hello() { console.log("Hello!"); } button.addEventListener("mouseover", hello); button.removeEventListener("mouseover", hello); Important: removeEventListener only works if you pass the same function reference.
Event Listener Options
| Option | Description |
|---|---|
| once | Runs handler only once |
| capture | Runs during capture phase |
| passive | Improves scroll performance |
window.addEventListener("scroll", logScroll, { passive: true, once: false, capture: false }); The Event Object
Every event automatically receives an event object with powerful properties.
document.addEventListener("click", (event) => { console.log(event.target); console.log(event.type); }); Common Properties
- event.target → element on which event occurred
- event.currentTarget → element with the listener
- event.preventDefault() → stop default action
- event.stopPropagation() → stop bubbling
- event.key (keyboard)
- event.which (mouse buttons)
Event Propagation
When an event occurs, it moves through three phases:
CAPTURING → TARGET → BUBBLING
1. Capturing Phase
Event moves from top → down (window → element).
2. Target Phase
Event reaches the actual element.
3. Bubbling Phase
Event moves from down → top (element → window).
Most events bubble by default.
parent.addEventListener("click", () => console.log("Parent"), true); // capturing child.addEventListener("click", () => console.log("Child")); // bubbling stopPropagation() vs stopImmediatePropagation()
event.stopPropagation(); // stops bubbling or capturing beyond this element event.stopImmediatePropagation(); // stops all other listeners on same element too Event Delegation
Event delegation is a technique where you attach one event listener to a parent instead of each child element.
Diagram
Parent ┗━ Child 1 ┗━ Child 2 ┗━ Child 3
Example: Todo list click handler
document.querySelector("#list").addEventListener("click", (event) => { if(event.target.tagName === "LI") { console.log("Item clicked:", event.target.textContent); } }); This is used heavily in dynamic UIs (including LWC DOM rendering).
Advanced JavaScript Event
Concepts
Event Loop
The event loop manages:
- Call stack
- Microtask queue
- Macrotask queue
Example
console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Execution order:
Start End Promise Timeout
Debouncing (Improving Performance)
Used when user types — prevents too many function calls.
function debounce(fn, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } const searchHandler = debounce(() => { console.log("Searching..."); }, 500); Throttling
Controls how often a function executes during continuous actions like scrolling.
function throttle(fn, limit) { let waiting = false; return function(...args) { if (!waiting) { fn.apply(this, args); waiting = true; setTimeout(() => waiting = false, limit); } }; } window.addEventListener("scroll", throttle(() => { console.log("Scrolling..."); }, 300)); Custom Events in JavaScript
const event = new CustomEvent("helloEvent", { detail: { message: "Hello Peoplewoo!" }, bubbles: true, composed: true }); element.dispatchEvent(event); Real-Life Project Examples
1. Search Bar with Debouncing
2. Modal Open/Close Events
3. Form Validation on Input Events
4. Infinite Scroll using Scroll Event
5. Apex Call Triggered by Button Click in LWC
Interview Questions
Beginner
- What is an event in JavaScript?
- Difference between target and currentTarget?
- What is event bubbling?
Intermediate
- Explain event delegation with example.
- What is the difference between preventDefault and stopPropagation?
Advanced (LWC + JS)
- How does event propagation work inside Shadow DOM?
- When should composed: true be used in LWC?
- Explain microtask queue vs macrotask queue.
Frequently Asked Questions (FAQ)
Conclusion
JavaScript events are the foundation of all interactive web applications. From simple click handlers to complex event propagation, debouncing, custom events, and LWC communication — mastering events allows you to build fast, dynamic, and user-friendly experiences.
More SFDC Resources
Start your SFMC journey today — join our Live Training
Need help? Chat with us on WhatsApp anytime.
Learn. Practice. Get Certified. Succeed with Peoplewoo Skills.
