What are Events?
How the browser signals that something happened — and how JavaScript responds.
1. Introduction
JavaScript code does not run continuously. Most of the time it is idle, waiting for something to happen. That "something" is an event: the user clicks a button, presses a key, moves the mouse, submits a form, or the page finishes loading.
The browser fires events constantly. Your job is to write event handlers — functions that run when a specific event occurs on a specific element. This is the event-driven programming model that powers every interactive web page.
2. Theory
2.1 What is an event?
An event is a signal that something happened in the browser. Events can come from:
- User actions — click, keydown, submit, scroll, resize
- Browser lifecycle — DOMContentLoaded, load, unload
- Network — fetch responses, WebSocket messages
- Timers — setTimeout, setInterval callbacks
2.2 The Event object
When an event fires, the browser creates an Event object with details about what happened and passes it to your handler function:
document.querySelector('button').addEventListener('click', function(event) {
console.log(event.type); // 'click'
console.log(event.target); // the button element that was clicked
console.log(event.timeStamp); // when it happened
console.log(event.clientX, event.clientY); // mouse position (MouseEvent)
});
The parameter is usually named event, evt, or e by convention.
2.3 The three phases of an event
When an event fires, it travels through three phases:
- Capture phase — travels down from the document root to the target element
- Target phase — reaches the element that fired the event
- Bubble phase — travels back up to the document root
By default, event listeners fire in the bubble phase. You will learn more about bubbling in Lesson 4.
2.4 Three ways to listen for events
1. HTML inline (avoid)
<button onclick="handleClick()">Click</button>
Mixes HTML and JavaScript. Hard to maintain. Cannot easily add/remove.
2. DOM property (older, limited)
const btn = document.querySelector('button');
btn.onclick = function() { console.log('clicked'); };
// Can only assign ONE handler per event type
3. addEventListener (correct approach)
const btn = document.querySelector('button');
btn.addEventListener('click', function() { console.log('clicked'); });
// Can add multiple handlers. Can remove them. Supports options.
2.5 The DOMContentLoaded event
Fires when the HTML is fully parsed and the DOM is built — before images/stylesheets finish loading.
document.addEventListener('DOMContentLoaded', () => {
// Safe to access any DOM element here
const btn = document.querySelector('#my-btn');
btn.addEventListener('click', handleClick);
});
// Alternative: place scripts at bottom of body with defer attribute
// Both approaches ensure the DOM is ready
2.6 Event-driven flow
// 1. Page loads — initial setup
const counter = document.querySelector('#counter');
let count = 0;
// 2. Register listener — nothing runs yet
document.querySelector('#increment').addEventListener('click', () => {
// 3. User clicks — THIS code runs
count++;
counter.textContent = count;
});
// 4. Back to idle — waiting for next event
3. Real World Example
A social media "Like" button uses three events:
const likeBtn = document.querySelector('#like-btn');
const likeCount = document.querySelector('#like-count');
let liked = false;
let count = 1204;
// Click — toggle like state
likeBtn.addEventListener('click', () => {
liked = !liked;
count += liked ? 1 : -1;
likeCount.textContent = count;
likeBtn.classList.toggle('liked', liked);
likeBtn.setAttribute('aria-pressed', liked);
});
// mouseenter/mouseleave — hover effect
likeBtn.addEventListener('mouseenter', () => likeBtn.classList.add('hovered'));
likeBtn.addEventListener('mouseleave', () => likeBtn.classList.remove('hovered'));
// keydown — keyboard accessibility
likeBtn.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
likeBtn.click(); // trigger the click handler
}
});
4. Code Example
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Events Intro</title></head>
<body>
<h1>Event Explorer</h1>
<button id="demo-btn">Click or Press Enter</button>
<input type="text" id="demo-input" placeholder="Type here">
<ul id="event-log"></ul>
<script>
const log = document.querySelector('#event-log');
function logEvent(msg) {
const li = document.createElement('li');
li.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
log.prepend(li); // newest at top
}
const btn = document.querySelector('#demo-btn');
btn.addEventListener('click', e => {
logEvent(`click — target: ${e.target.tagName}, pos: (${e.clientX}, ${e.clientY})`);
});
btn.addEventListener('mouseenter', () => logEvent('mouseenter'));
btn.addEventListener('mouseleave', () => logEvent('mouseleave'));
const input = document.querySelector('#demo-input');
input.addEventListener('focus', () => logEvent('focus'));
input.addEventListener('blur', () => logEvent('blur'));
input.addEventListener('input', e => logEvent(`input value: "${e.target.value}"`));
document.addEventListener('keydown', e => {
logEvent(`keydown: "${e.key}" (code: ${e.code})`);
});
</script>
</body>
</html>
5. Code Breakdown
logEvent helper
Creates a new list item with a timestamp and the event description. log.prepend(li) puts the newest entry at the top so you can see recent events without scrolling.
e.target.tagName and e.clientX/Y
Properties of the MouseEvent object. target is the element that was clicked. clientX/Y are pixel coordinates from the top-left of the browser viewport.
e.target.value in the input event
The input event fires on every keystroke. e.target is the input element, and .value is its current text content — the best way to read live form input.
document-level keydown listener
Attaching the listener to document catches keyboard events no matter which element is focused. This is the correct approach for global keyboard shortcuts.
6. Common Mistakes
Mistake 1 — Calling the function in addEventListener
// Bad — calls handleClick() immediately and passes its return value
btn.addEventListener('click', handleClick()); // undefined as handler
// Good — pass the function reference
btn.addEventListener('click', handleClick);
Mistake 2 — Adding listeners before the DOM loads
// Bad — runs before body is parsed
<head><script> document.querySelector('#btn').addEventListener(...) </script></head>
// Good — bottom of body, or defer, or DOMContentLoaded
Mistake 3 — Using onclick instead of addEventListener
// Bad — second assignment overwrites the first
btn.onclick = handler1;
btn.onclick = handler2; // handler1 is lost
// Good — both run
btn.addEventListener('click', handler1);
btn.addEventListener('click', handler2);
7. Best Practices
- Always use addEventListener — never inline onclick attributes.
- Name your handler functions descriptively — easier to remove them later with removeEventListener.
- Use DOMContentLoaded or defer to ensure the DOM is ready before attaching listeners.
- Always receive the event object as a parameter — you will often need
e.target,e.preventDefault(), ore.key. - Remove listeners when no longer needed (e.g., on component unmount) to prevent memory leaks.
8. Practice Exercise
- Create a page with a button, an input, and a div. Attach these events and log each to the console: click on button, focus/blur on input, input on input (log current value), and mousemove on the div (log mouse position).
- Build a "color picker": three range inputs for R, G, B (0–255). On every input event, update a box's background color using
rgb(R, G, B).
9. Assignment
Build an "Event Dashboard" that visualises browser events in real time.
- Create a page with several interactive elements.
- Track and display a live count of: total clicks, keypresses, mouse movements (throttled to every 100ms), focus events, and scroll events.
- Show the last 5 events in a list with type, target, and timestamp.
- Add a "Pause" / "Resume" button that stops/starts logging events.
Deliverable: One HTML file.
10. Interview Questions
- What is an event in JavaScript?
A signal from the browser that something happened — a user action, a browser lifecycle moment, or a timer. JavaScript responds by running event handler functions. - What is an Event object?
An object created by the browser when an event fires, passed as the first argument to the handler. Contains details about the event: type, target element, mouse position, key pressed, etc. - Why use addEventListener instead of onclick?
addEventListener allows multiple handlers for the same event type, supports capture phase, and can be removed with removeEventListener. onclick only allows one handler and is overwritten silently. - What is event.target?
The DOM element that the event originated from — the specific element that was clicked/focused/etc. Different from event.currentTarget, which is the element the listener is attached to.
11. Additional Resources
- MDN — Introduction to events
- MDN — EventTarget.addEventListener()
- javascript.info — Introduction to browser events