JavaScript Notes
Learn JavaScript Event Object properties & methods. Covers event.target, preventDefault, stopPropagation, MouseEvent, KeyboardEvent with examples.
Introduction
Whenever an event occurs in the browser — whether the user clicked, pressed a key, or moved the mouse — the browser automatically creates an Event Object and passes it to the event handler function as the first parameter.
This Event Object is like a treasure box — it contains all the information about the event: what happened, where it happened, which element it happened on, and much more.
button.addEventListener('click', function(event) {
// 'event' yahan Event Object hai
// Browser ne ise automatically pass kiya
console.log(event);
});PointerEvent {isTrusted: true, type: "click", target: button, currentTarget: button, ...}Key Point: You don't need to create the event object manually — the browser creates it automatically and passes it as the first parameter to the handler function. You can name it anything: event, e, or evt.
Key Properties of Event Object
1. event.type
This property tells which event was triggered — "click", "keydown", "submit", etc.
document.addEventListener('click', function(event) {
console.log("Event type:", event.type);
});
document.addEventListener('keydown', function(event) {
console.log("Event type:", event.type);
});Event type: click Event type: keydown
2. event.target
This returns the actual element on which the event occurred. If you clicked inside nested elements, this will be the innermost (deepest) element.
// HTML: <div id="parent"><button id="child">Click Me</button></div>
document.getElementById('parent').addEventListener('click', function(event) {
console.log("Target element:", event.target.id);
console.log("Target tag:", event.target.tagName);
});
// User clicks the button inside divTarget element: child Target tag: BUTTON
3. event.currentTarget
This is the element on which the event listener is attached. It is very important in event delegation.
// HTML: <ul id="menu"><li>Home</li><li>About</li></ul>
document.getElementById('menu').addEventListener('click', function(event) {
console.log("target:", event.target.tagName); // LI (jahan click hua)
console.log("currentTarget:", event.currentTarget.tagName); // UL (jahan listener hai)
});
// User clicks on "Home" litarget: LI currentTarget: UL
4. event.bubbles
A boolean value that indicates whether the event will bubble or not. Most events bubble, but some (like focus, blur) do not.
document.addEventListener('click', function(event) {
console.log("Click bubbles:", event.bubbles);
});
document.querySelector('input').addEventListener('focus', function(event) {
console.log("Focus bubbles:", event.bubbles);
});Click bubbles: true Focus bubbles: false
5. event.clientX / event.clientY
In mouse events, these properties give the cursor position relative to the viewport (visible area).
document.addEventListener('mousemove', function(event) {
console.log(`Mouse position: X=${event.clientX}, Y=${event.clientY}`);
});
// User moves mouse to coordinates (150, 300)Mouse position: X=150, Y=300
6. event.key
In keyboard events, this property indicates which key was pressed. It is the modern replacement for the deprecated keyCode.
document.addEventListener('keydown', function(event) {
console.log("Key pressed:", event.key);
console.log("Key code:", event.code);
console.log("Shift held:", event.shiftKey);
});
// User presses Shift + AKey pressed: A Key code: KeyA Shift held: true
7. event.timeStamp
When the event was triggered — gives the time in milliseconds since page load.
document.addEventListener('click', function(event) {
console.log("Event occurred at:", event.timeStamp.toFixed(2), "ms after page load");
});Event occurred at: 4523.70 ms after page load
8. event.isTrusted
Indicates whether the event was triggered by a user action (true) or dispatched programmatically (false).
button.addEventListener('click', function(event) {
console.log("Is user-triggered:", event.isTrusted);
});
// User clicks → true
// button.click() → true (browser simulates)
// button.dispatchEvent(new Event('click')) → falseIs user-triggered: true
Code Examples
Example 1: Accessing All Basic Properties
const btn = document.querySelector('#myBtn');
btn.addEventListener('click', function(event) {
console.log("Type:", event.type);
console.log("Target:", event.target.id);
console.log("CurrentTarget:", event.currentTarget.id);
console.log("Bubbles:", event.bubbles);
console.log("Trusted:", event.isTrusted);
console.log("TimeStamp:", Math.round(event.timeStamp));
});
// User clicks button#myBtnType: click Target: myBtn CurrentTarget: myBtn Bubbles: true Trusted: true TimeStamp: 5234
Example 2: Mouse Coordinates (All Types)
document.addEventListener('click', function(event) {
console.log("=== Mouse Coordinates ===");
console.log("clientX/Y (viewport):", event.clientX, event.clientY);
console.log("pageX/Y (page):", event.pageX, event.pageY);
console.log("screenX/Y (screen):", event.screenX, event.screenY);
console.log("offsetX/Y (element):", event.offsetX, event.offsetY);
});
// User clicks at a position on page=== Mouse Coordinates === clientX/Y (viewport): 245 180 pageX/Y (page): 245 680 screenX/Y (screen): 545 380 offsetX/Y (element): 45 20
Example 3: Keyboard Event Details
document.addEventListener('keydown', function(event) {
console.log("Key:", event.key);
console.log("Code:", event.code);
console.log("Alt:", event.altKey);
console.log("Ctrl:", event.ctrlKey);
console.log("Shift:", event.shiftKey);
console.log("Meta (Win/Cmd):", event.metaKey);
console.log("Repeat:", event.repeat);
});
// User presses Ctrl + SKey: s Code: KeyS Alt: false Ctrl: true Shift: false Meta (Win/Cmd): false Repeat: false
Example 4: Form Submit Event
const form = document.querySelector('#loginForm');
form.addEventListener('submit', function(event) {
event.preventDefault(); // Form submit hone se roko
console.log("Event type:", event.type);
console.log("Submitter:", event.submitter.textContent);
console.log("Default prevented:", event.defaultPrevented);
// Handle form data manually
const formData = new FormData(form);
console.log("Username:", formData.get('username'));
});
// User clicks submit buttonEvent type: submit Submitter: Login Default prevented: true Username: rahul123
Example 5: Event Delegation with target
// HTML: <ul id="todo-list">
// <li data-id="1">Buy groceries</li>
// <li data-id="2">Read book</li>
// <li data-id="3">Exercise</li>
// </ul>
const list = document.getElementById('todo-list');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
const itemId = event.target.dataset.id;
const itemText = event.target.textContent;
console.log(`Clicked item #${itemId}: "${itemText}"`);
console.log("Listener on:", event.currentTarget.id);
}
});
// User clicks "Read book"Clicked item #2: "Read book" Listener on: todo-list
Example 6: Custom Event with Detail
// Creating a custom event
const customEvent = new CustomEvent('userLogin', {
detail: {
username: 'rahul_dev',
role: 'admin',
loginTime: new Date().toISOString()
},
bubbles: true
});
document.addEventListener('userLogin', function(event) {
console.log("Custom event type:", event.type);
console.log("Username:", event.detail.username);
console.log("Role:", event.detail.role);
console.log("Is trusted:", event.isTrusted);
});
document.dispatchEvent(customEvent);Custom event type: userLogin Username: rahul_dev Role: admin Is trusted: false
MouseEvent vs KeyboardEvent vs FocusEvent
JavaScript has different Event interfaces for different event types. All inherit from Event but bring their own extra properties.
Comparison Table
| Feature | MouseEvent | KeyboardEvent | FocusEvent |
|---|---|---|---|
| Trigger | Mouse click, move, hover | Key press/release | Focus gain/loss |
| Events | click, dblclick, mousedown, mousemove | keydown, keyup, keypress(deprecated) | focus, blur, focusin, focusout |
| Coordinates | ✅ clientX, pageX, screenX | ❌ Not available | ❌ Not available |
| Key info | ❌ Not available | ✅ key, code, modifiers | ❌ Not available |
| Bubbles | ✅ Yes | ✅ Yes | ⚠️ focus/blur: No, focusin/focusout: Yes |
| relatedTarget | ✅ (mouseenter/leave) | ❌ | ✅ (previous/next element) |
Example: Checking Event Type
document.addEventListener('click', function(event) {
console.log("Is MouseEvent:", event instanceof MouseEvent);
console.log("Is KeyboardEvent:", event instanceof KeyboardEvent);
});
document.addEventListener('keydown', function(event) {
console.log("Is MouseEvent:", event instanceof MouseEvent);
console.log("Is KeyboardEvent:", event instanceof KeyboardEvent);
});
// User clicks, then presses a keyIs MouseEvent: true Is KeyboardEvent: false Is MouseEvent: false Is KeyboardEvent: true
event.target vs event.currentTarget
This is the most confusing part of JavaScript events. Let's understand it clearly:
- event.target → Actual element on which the event occurred (the source)
- event.currentTarget → Element on which the event listener is registered
Detailed Example
// HTML:
// <div id="container">
// <div id="wrapper">
// <button id="action-btn">
// <span id="btn-text">Click Me</span>
// </button>
// </div>
// </div>
const container = document.getElementById('container');
container.addEventListener('click', function(event) {
console.log("=== target vs currentTarget ===");
console.log("target (clicked):", event.target.id);
console.log("currentTarget (listener):", event.currentTarget.id);
console.log("Are they same?", event.target === event.currentTarget);
});
// User clicks on the <span> text inside button=== target vs currentTarget === target (clicked): btn-text currentTarget (listener): container Are they same? false
When Are They Same?
const btn = document.getElementById('action-btn');
btn.addEventListener('click', function(event) {
console.log("target:", event.target.id);
console.log("currentTarget:", event.currentTarget.id);
console.log("Same?", event.target === event.currentTarget);
});
// User clicks DIRECTLY on button (not on child span)target: action-btn currentTarget: action-btn Same? true
Rule: Only when the user directly clicks the element that has the listener — that's when both are the same. If a child element is clicked and the event bubbles up, target will be different.
preventDefault() and stopPropagation()
event.preventDefault()
Prevents the default browser behavior. Has no effect on event propagation — the event will continue to bubble.
Common Use Cases:
- Form submission rokna
- Link navigation rokna
- Context menu (right-click) rokna
- Checkbox toggle rokna
// Example 1: Form submit rokna
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
console.log("Form submitted? No! Default prevented.");
console.log("defaultPrevented:", event.defaultPrevented);
// Do custom validation and AJAX call here
});Form submitted? No! Default prevented. defaultPrevented: true
// Example 2: Link click rokna
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault();
console.log("Link href:", event.target.href);
console.log("Navigation blocked! Custom handling...");
});Link href: https://example.com/page Navigation blocked! Custom handling...
event.stopPropagation()
Stops the event from bubbling up to parent elements. Other listeners on the current element will still run, but the event won't reach the parent.
// HTML: <div id="parent"><button id="child">Click</button></div>
document.getElementById('parent').addEventListener('click', function(event) {
console.log("Parent clicked!"); // This will NOT run
});
document.getElementById('child').addEventListener('click', function(event) {
event.stopPropagation();
console.log("Child clicked! Propagation stopped.");
console.log("Event will NOT reach parent.");
});
// User clicks child buttonChild clicked! Propagation stopped. Event will NOT reach parent.
event.stopImmediatePropagation()
This is stricter than stopPropagation() — even other listeners on the same element won't run.
const btn = document.querySelector('#btn');
btn.addEventListener('click', function(event) {
console.log("First listener runs");
event.stopImmediatePropagation();
});
btn.addEventListener('click', function(event) {
console.log("Second listener runs"); // This will NOT run
});
// User clicks buttonFirst listener runs
Comparison: preventDefault vs stopPropagation
// Demonstrating that preventDefault doesn't stop bubbling
// HTML: <div id="outer"><a id="link" href="/page">Go</a></div>
document.getElementById('outer').addEventListener('click', function(event) {
console.log("Parent handler still runs!"); // Runs because bubbling not stopped
});
document.getElementById('link').addEventListener('click', function(event) {
event.preventDefault(); // Only prevents navigation, NOT bubbling
console.log("Link click prevented, but event still bubbles");
});
// User clicks linkLink click prevented, but event still bubbles Parent handler still runs!
🚫 Common Mistakes
Mistake 1: Forgetting the event parameter
// ❌ WRONG - event variable not defined
button.addEventListener('click', function() {
console.log(event.target); // 'event' is undefined in strict mode
});
// ✅ CORRECT - accept event as parameter
button.addEventListener('click', function(event) {
console.log(event.target);
});// ❌ Uncaught ReferenceError: event is not defined // ✅ <button id="myBtn">Click</button>
Mistake 2: Using event.target instead of event.currentTarget for styling
// ❌ WRONG - target might be a child element
container.addEventListener('click', function(event) {
event.target.classList.add('active'); // Might style wrong element!
});
// ✅ CORRECT - currentTarget is always the listener element
container.addEventListener('click', function(event) {
event.currentTarget.classList.add('active'); // Always styles container
});// ❌ If user clicks a <span> inside container, span gets 'active' class // ✅ Container always gets 'active' class regardless of click position
Mistake 3: Assuming all events bubble
// ❌ WRONG - focus doesn't bubble
parentDiv.addEventListener('focus', function(event) {
console.log("Focus detected!"); // Never fires via bubbling!
});
// ✅ CORRECT - use focusin which bubbles
parentDiv.addEventListener('focusin', function(event) {
console.log("Focus detected via focusin!");
console.log("Focused element:", event.target.tagName);
});// ❌ (nothing happens when child input gets focus) // ✅ Focus detected via focusin! // ✅ Focused element: INPUT
Mistake 4: Using deprecated keyCode instead of key
// ❌ WRONG - keyCode is deprecated
document.addEventListener('keydown', function(event) {
if (event.keyCode === 13) { // Magic number, hard to read
console.log("Enter pressed");
}
});
// ✅ CORRECT - use event.key
document.addEventListener('keydown', function(event) {
if (event.key === 'Enter') { // Clear and readable
console.log("Enter pressed");
}
});Enter pressed Enter pressed
Mistake 5: Stopping propagation unnecessarily (breaking event delegation)
// ❌ WRONG - breaks parent delegation
childButton.addEventListener('click', function(event) {
event.stopPropagation(); // Now parent can't track clicks!
doSomething();
});
// Parent's analytics tracking broke:
document.addEventListener('click', function(event) {
trackClick(event.target); // Never receives child button clicks
});
// ✅ CORRECT - handle locally without stopping propagation
childButton.addEventListener('click', function(event) {
doSomething(); // Handle your logic
// Don't stop propagation unless absolutely necessary
});// ❌ Parent click tracker never fires for child button // ✅ Both child handler AND parent tracker work correctly
Mistake 6: Confusing preventDefault with return false
// ❌ WRONG - return false only works in inline HTML handlers
button.addEventListener('click', function(event) {
return false; // Does NOTHING in addEventListener!
});
// ✅ CORRECT - use preventDefault()
button.addEventListener('click', function(event) {
event.preventDefault(); // Actually prevents default action
});
// Note: return false works in jQuery and inline onclick="return false"
// but NOT in addEventListener// ❌ Default action still happens (return false ignored) // ✅ Default action prevented successfully
Mistake 7: Accessing event object asynchronously
// ❌ WRONG - event object may be nullified/reused
button.addEventListener('click', function(event) {
setTimeout(function() {
console.log(event.type); // Might be null in some frameworks (React synthetic events)
}, 1000);
});
// ✅ CORRECT - save needed values immediately
button.addEventListener('click', function(event) {
const eventType = event.type;
const targetId = event.target.id;
setTimeout(function() {
console.log(eventType); // Safe - primitive value saved
console.log(targetId); // Safe - primitive value saved
}, 1000);
});// ❌ May log null or throw error (framework-dependent) // ✅ click // ✅ myBtn
🎯 Key Takeaways
- Event Object is automatically provided — The browser passes it as the first parameter to the event handler. You just need to accept the parameter.
- event.target ≠ event.currentTarget —
targetis where the event actually occurred,currentTargetis where the listener is registered. This difference is critical in delegation.
- preventDefault() only stops default behavior — It stops navigation, form submit, etc., but the event continues to bubble.
- stopPropagation() only stops bubbling — The event won't reach parent elements, but the default browser action will still occur.
- Not all events bubble —
focus,blur,mouseenter,mouseleavedon't bubble. Use their bubbling alternatives (focusin,focusout).
- Use event.key, not keyCode —
keyCodeis deprecated. Always useevent.keyorevent.codein modern code.
- MouseEvent has multiple coordinate systems —
clientX/Y(viewport),pageX/Y(document),screenX/Y(monitor),offsetX/Y(element). Choose based on your needs.
- Custom Events can be created — Create your own events with custom data using
new CustomEvent('name', { detail: data }).
- event.isTrusted is important for security — User-triggered events return
true, programmatic events returnfalse. Check this for security-sensitive operations.
- stopImmediatePropagation() is the strictest — It blocks even other listeners on the same element. Use sparingly.
❓ Interview Questions
Q1: What is the Event Object in JavaScript?
Answer: The Event Object is a browser-generated object that is automatically passed as the first parameter to the event handler function. It contains complete information about the event — type, target element, position, keys pressed, timestamp, and methods to control propagation.
Q2: What is the difference between event.target and event.currentTarget?
Answer:
event.target— Actual element on which the event originated (deepest element in DOM)event.currentTarget— Element on which addEventListener was called
In event delegation, currentTarget is the parent (where the listener is attached) and target is the actual clicked child. Inside the handler, this (in non-arrow functions) also equals currentTarget.
Q3: What is the difference between preventDefault() and stopPropagation()?
Answer:
preventDefault()— Stops the browser's default action (e.g., form submit, link navigate). Has no effect on event propagation.stopPropagation()— Stops the event from bubbling up to parent elements. Has no effect on the default action.
Both are independent — they don't affect each other. You can use both simultaneously.
Q4: Which events do NOT bubble?
Answer: Common non-bubbling events:
focus/blur(usefocusin/focusoutfor bubbling)mouseenter/mouseleave(usemouseover/mouseoutfor bubbling)load/unload/error(on elements)resize/scroll(on window)
You can verify by checking the event.bubbles property.
Q5: How do you create and dispatch custom events?
Answer:
// Create custom event with data
const event = new CustomEvent('orderPlaced', {
detail: { orderId: 'ORD-123', amount: 999 },
bubbles: true,
cancelable: true
});
// Listen for it
element.addEventListener('orderPlaced', function(e) {
console.log(e.detail.orderId); // 'ORD-123'
});
// Dispatch it
element.dispatchEvent(event);ORD-123
Custom events always have isTrusted set to false because they are created programmatically.
Q6: What is event.composedPath()?
Answer: event.composedPath() returns an array representing the event's propagation path — including all elements from the target to the window.
["BUTTON", "DIV", "SECTION", "BODY", "HTML", "HTMLDocument", "Window"]
This also shows the path through Shadow DOM, which is useful for debugging and complex component architectures.
Q7: What is the difference between event.key and event.code?
Answer:
event.key— The logical name of the character or key ("a", "A", "Enter", "ArrowUp"). Changes according to the keyboard layout.event.code— Physical key identifier ("KeyA", "Enter", "ArrowUp"). Independent of keyboard layout.
Use case: Use event.code in games (physical position matters), use event.key for text input (actual character matters).
// When pressing the 'A' position on an AZERTY keyboard:
// event.key = "q" (AZERTY layout)
// event.code = "KeyA" (physical key same hai)key: q code: KeyA
📝 FAQ
Q: Can the event object be stored in a variable?
Answer: Yes, in vanilla JavaScript the event object persists. However, in React's synthetic events, they are recycled — if you need to use it in an async operation, extract the values first or call event.persist().
Q: Is it necessary to name the event parameter "event"?
Answer: No, you can name it anything — e, evt, ev, or anything else. It's just a function parameter. By convention, event or e is commonly used:
click
Q: Is the event object available in arrow functions?
Answer: Yes! Arrow functions also receive the event object as the first parameter. The only difference is that this in an arrow function is lexical (from the parent scope), whereas in a regular function this refers to currentTarget.
click true true
Q: What other useful properties in the event object are lesser known?
Answer: Some lesser-known but powerful properties:
event.composedPath()— Full propagation path arrayevent.defaultPrevented— Check if preventDefault already calledevent.eventPhase— 1 (capture), 2 (target), 3 (bubble)event.detail— Click count (dblclick = 2) ya custom dataevent.relatedTarget— Related element in Mouse/Focus events
Q: Do multiple event listeners receive the same event object?
Answer: Yes, when a single event is triggered, all listeners receive the same event object. If one listener calls stopImmediatePropagation(), subsequent listeners won't receive this object.
First: hello Second: hello
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Event Object – Complete Guide with Examples (2026).
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, events, event, object
Related JavaScript Master Course Topics