JavaScript Events
JavaScript Events Interview with follow-up questions
1. What is an event in JavaScript?
An event is a signal that something has happened in the browser — a user action like a click, keydown, input, or submit, or something system/programmatic like load, DOMContentLoaded, a network response, or a timer firing.
You respond to events by registering a handler with addEventListener(type, handler, options). When the event fires, the browser calls your handler and passes an event object describing what happened (event.target, event.type, coordinates, key pressed, etc.).
button.addEventListener('click', (event) => {
console.log(event.type, event.target);
});
Events are the backbone of the browser's asynchronous, non-blocking model: the event loop dispatches them to your handlers as they occur, rather than you polling for changes.
Follow-up 1
Can you explain the difference between a user-generated event and a system-generated event?
A user-generated event is triggered by the user's interaction with the webpage, such as clicking a button or typing in an input field. These events are directly initiated by the user's actions. On the other hand, a system-generated event is triggered by the browser or the webpage itself, without any direct user interaction. Examples of system-generated events include the page finishing loading, a timer expiring, or an error occurring.
Follow-up 2
What are some common examples of JavaScript events?
There are many types of JavaScript events, but some common examples include:
- Click event: triggered when an element is clicked
- Submit event: triggered when a form is submitted
- Keydown event: triggered when a key is pressed down
- Mouseover event: triggered when the mouse pointer enters an element
- Load event: triggered when a webpage finishes loading
- Error event: triggered when an error occurs
These are just a few examples, and there are many more events available in JavaScript.
Follow-up 3
How does event handling work in JavaScript?
In JavaScript, event handling involves writing code to respond to specific events. This code is typically written as event handlers, which are functions that are executed when the specified event occurs. Event handlers can be attached to HTML elements using the addEventListener method or by assigning a function directly to the element's event property.
Here's an example of attaching an event handler to a button element:
const button = document.querySelector('button');
button.addEventListener('click', function() {
// Code to be executed when the button is clicked
});
When the button is clicked, the function specified as the event handler will be executed. Event handling allows developers to create interactive and dynamic webpages by responding to user actions and system events.
2. How can you register an event handler in JavaScript?
Use addEventListener(type, handler, options) — the standard way. Avoid inline onclick="..." HTML attributes and the element.onclick = fn property assignment, since both only allow a single handler and mix markup with behavior.
const button = document.querySelector('#myButton');
const handleClick = (event) => {
console.log('clicked', event.currentTarget);
};
button.addEventListener('click', handleClick);
The third argument is an options object. The most useful in 2026:
button.addEventListener('click', handleClick, {
once: true, // auto-remove after first fire
passive: true, // promise not to call preventDefault() (scroll/touch perf)
capture: false, // listen in bubbling (default) vs capturing phase
signal: controller.signal, // remove via AbortController.abort()
});
Follow-up — removing handlers: pass the same function reference to removeEventListener, or better, use an AbortController signal and call controller.abort() to tear down one or many listeners at once.
Follow-up 1
What is the difference between using addEventListener and setting an on-event property?
The main difference between using addEventListener and setting an on-event property is that addEventListener allows you to register multiple event handlers for the same event on the same element, while setting an on-event property can only have one event handler.
Here's an example:
const button = document.querySelector('#myButton');
// Using addEventListener
button.addEventListener('click', function() {
// code to be executed when the button is clicked
});
// Using on-event property
button.onclick = function() {
// code to be executed when the button is clicked
};
In this example, addEventListener allows you to add multiple click event handlers, while setting onclick property can only have one click event handler.
Follow-up 2
Can you register multiple event handlers for the same event on the same element?
Yes, you can register multiple event handlers for the same event on the same element using the addEventListener method. Here's an example:
const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
// code to be executed when the button is clicked (handler 1)
});
button.addEventListener('click', function() {
// code to be executed when the button is clicked (handler 2)
});
In this example, we're registering two click event handlers for the same button element. Both handlers will be executed when the button is clicked.
Follow-up 3
What happens if an event handler is registered twice for the same event on the same element?
If an event handler is registered twice for the same event on the same element using addEventListener, both handlers will be executed when the event occurs. The order of execution will be the same as the order in which the handlers were registered.
Here's an example:
const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
console.log('Handler 1');
});
button.addEventListener('click', function() {
console.log('Handler 2');
});
In this example, when the button is clicked, both Handler 1 and Handler 2 will be logged to the console.
3. What is event propagation in JavaScript?
Event propagation is how an event travels through the DOM tree in three phases when it fires on a target:
- Capturing — from
window/documentdown to the target's parent. - Target — the event reaches the element it occurred on.
- Bubbling — back up from the target through its ancestors to the root.
By default, addEventListener listens in the bubbling phase; pass { capture: true } to listen during the capture phase instead. (Note: "bubbling" is only the third phase, not the whole story — propagation includes capturing too.)
You can control propagation from inside a handler:
parent.addEventListener('click', (event) => {
event.stopPropagation(); // stop event reaching further ancestors
// event.stopImmediatePropagation(); // also skip other handlers on this element
});
stopPropagation() does not prevent the element's default action — use preventDefault() for that. Also note target (what triggered the event) differs from currentTarget (the element whose handler is running).
Follow-up 1
What is the difference between event bubbling and event capturing?
Event bubbling and event capturing are two different phases of event propagation.
Event bubbling is the default behavior in which an event is first handled by the innermost element and then propagated to its parent elements.
Event capturing is the opposite behavior in which an event is first handled by the outermost element and then propagated to its child elements.
To specify which phase to use, you can use the addEventListener method with the useCapture parameter set to true for event capturing, or false (default) for event bubbling.
Follow-up 2
How can you stop event propagation?
To stop event propagation, you can use the stopPropagation() method of the event object. This method prevents the event from propagating further up or down the DOM tree.
Example:
const button = document.querySelector('button');
button.addEventListener('click', function(event) {
event.stopPropagation();
// Event propagation stopped here
});
Follow-up 3
What are the implications of stopping event propagation?
Stopping event propagation can have several implications:
- Other event handlers attached to parent or child elements will not be triggered.
- Event delegation, where you attach a single event handler to a parent element to handle events on its child elements, will not work for the stopped event.
- If multiple event handlers are attached to the same element, stopping event propagation will prevent the remaining event handlers from being executed.
It is important to use stopPropagation() carefully and consider its implications in your application's event handling logic.
4. What is the event object in JavaScript?
The event object is automatically passed as the first argument to every event handler. It carries everything about the event and exposes methods to control its behavior.
element.addEventListener('click', (event) => {
event.target; // the element that actually triggered the event
event.currentTarget; // the element the handler is attached to
event.type; // 'click'
event.preventDefault(); // cancel the default action (e.g. form submit, link nav)
event.stopPropagation(); // stop it from reaching other elements
});
Key distinction interviewers probe: target vs currentTarget. With event delegation, currentTarget is the parent you bound the listener to, while target is the descendant actually clicked — they're often different.
Specialized event types extend the base with extra fields: MouseEvent adds clientX/clientY and button; KeyboardEvent adds key and code; InputEvent carries the input data. Don't rely on the deprecated event.keyCode — use event.key.
Follow-up 1
What information does the event object provide?
The event object provides various information about the event, including:
event.type: The type of event that occurred (e.g., 'click', 'keydown', 'mouseover').event.target: The element on which the event was originally triggered.event.currentTarget: The element that the event handler is currently attached to.event.preventDefault(): A method to prevent the default behavior of the event.event.stopPropagation(): A method to stop the event from propagating to parent elements.- Additional properties and methods specific to the type of event.
Follow-up 2
How can you use the event object to handle events more effectively?
To handle events more effectively using the event object, you can:
Access the target element: Use
event.targetto reference the element on which the event occurred. This allows you to manipulate or retrieve information about the specific element.Prevent default behavior: Use
event.preventDefault()to prevent the default behavior associated with the event. For example, you can prevent a form from being submitted or prevent a link from navigating to a new page.Stop event propagation: Use
event.stopPropagation()to stop the event from propagating to parent elements. This can be useful when you want to handle an event only on a specific element and prevent it from triggering the same event on parent elements.Access additional event data: Depending on the type of event, the event object may provide additional properties or methods that allow you to access specific data related to the event. For example, for a mouse event, you can access the mouse coordinates using
event.clientXandevent.clientY.
Follow-up 3
What is the difference between the target and currentTarget properties on the event object?
The event.target property refers to the element on which the event was originally triggered, while the event.currentTarget property refers to the element that the event handler is currently attached to.
event.target: This property always points to the element that triggered the event, regardless of where the event handler is attached. For example, if you have a click event on a button element,event.targetwill be the button element itself.event.currentTarget: This property points to the element that the event handler is currently attached to. It can be useful when you have event delegation, where you attach a single event handler to a parent element and handle events for its child elements. In this case,event.currentTargetwill be the parent element, even if the event was triggered on a child element.
In most cases, you can use either event.target or event.currentTarget depending on your specific needs.
5. How can you simulate a user event in JavaScript?
Create an event with the appropriate constructor and dispatch it with dispatchEvent(). Use the specific event interface (MouseEvent, KeyboardEvent) so the handler receives the right properties, or CustomEvent to carry your own data via detail.
const button = document.querySelector('button');
const event = new MouseEvent('click', { bubbles: true, cancelable: true });
button.dispatchEvent(event);
For custom application-level events:
el.dispatchEvent(new CustomEvent('user:save', {
detail: { id: 42 },
bubbles: true,
}));
Gotchas: set bubbles: true if you want delegation/ancestor handlers to fire — synthetic events don't bubble by default. The old document.createEvent() / initEvent() API is deprecated; use the constructors above. Note that for some elements a real el.click() is simpler, and dispatched events don't trigger native default behavior the way trusted (user-generated) events do (event.isTrusted is false).
Follow-up 1
What is the purpose of simulating user events?
Simulating user events can be useful in various scenarios. Some common purposes include:
- Testing: Simulating user events allows you to automate testing of user interactions and ensure that your application behaves correctly.
- User experience: Simulating user events can help you simulate user interactions and provide a better user experience.
- Accessibility: Simulating user events can be used to test and ensure that your application is accessible to users with disabilities.
- Debugging: Simulating user events can help you debug and troubleshoot issues related to user interactions.
Follow-up 2
What are some common use cases for simulating user events?
Some common use cases for simulating user events include:
- Testing form submissions: Simulating a form submission event can be useful for testing form validation and submission logic.
- Testing user interactions: Simulating user events like clicks, key presses, and mouse movements can help you test and validate user interactions in your application.
- Automating repetitive tasks: Simulating user events can be used to automate repetitive tasks in your application.
- Creating custom UI components: Simulating user events can be used to create custom UI components that respond to user interactions.
Follow-up 3
Can you simulate system events as well?
No, you cannot simulate system events using JavaScript. System events, such as operating system-level events or hardware events, are outside the scope of JavaScript's capabilities. JavaScript can only simulate user events within the context of a web page or web application.
6. What are debouncing and throttling, and when would you use each?
A very common practical question for event-heavy UIs. Both limit how often a function runs in response to rapid events (scroll, resize, input, mousemove), but differently:
- Debounce — wait until the events stop for N ms, then run once. Good for search-as-you-type, autosave, validating after the user stops typing, resize-end.
- Throttle — run at most once every N ms during a continuous stream. Good for scroll handlers, drag, mousemove, infinite-scroll, rate-limited APIs.
function debounce(fn, delay) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), delay);
};
}
function throttle(fn, limit) {
let waiting = false;
return (...args) => {
if (waiting) return;
fn(...args);
waiting = true;
setTimeout(() => (waiting = false), limit);
};
}
Follow-ups: mention leading vs trailing edge variants, cancellation/flush, and that libraries (lodash debounce/throttle) handle the edge cases. For scroll-driven visibility work, IntersectionObserver is often better than a throttled scroll listener.
Live mock interview
Mock interview: JavaScript Events
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.