addEventListener and Event Object
Attach event listeners, receive the Event object, use preventDefault and stopPropagation, and understand event bubbling.
addEventListener and Event Object is a free Frontend Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Events?
Events are signals fired by the browser when something happens: a user clicks, presses a key, moves the mouse, the page loads, a network request completes. JavaScript reacts to events by attaching event listeners.
addEventListener Syntax
element.addEventListener(type, handler) attaches a function to run when the event fires. The handler receives an Event object with details about what happened.
const button = document.querySelector('#submit');
button.addEventListener('click', (event) => {
console.log('Button clicked!', event);
});Common Event Types
Mouse: click, dblclick, mouseenter, mouseleave, mousemove. Keyboard: keydown, keyup, keypress. Form: submit, input, change, focus, blur. Document: DOMContentLoaded, load. Window: resize, scroll.
// Form events:
input.addEventListener('input', (e) => console.log(e.target.value));
form.addEventListener('submit', handleSubmit);
// Window events:
window.addEventListener('resize', () => console.log(window.innerWidth));The Event Object
Every handler receives an Event object. Key properties: e.target (element that fired the event), e.currentTarget (element the listener is on), e.type (event name), e.timeStamp.
document.addEventListener('click', (e) => {
console.log(e.type); // 'click'
console.log(e.target); // element that was clicked
console.log(e.currentTarget); // element with the listener (document)
console.log(e.timeStamp); // ms since page load
});preventDefault()
event.preventDefault() stops the browser's default action. Use it to prevent form submission, prevent link navigation, or stop right-click context menus in games.
form.addEventListener('submit', (e) => {
e.preventDefault(); // stop page reload
// validate and process form data with JavaScript
});
link.addEventListener('click', (e) => {
e.preventDefault(); // handle SPA navigation manually
router.navigate(e.target.href);
});stopPropagation()
event.stopPropagation() stops the event from bubbling up through the DOM tree. Use it when an inner element's handler should not trigger the outer element's handler.
modal.addEventListener('click', (e) => {
e.stopPropagation(); // don't close modal when clicking inside it
});
document.addEventListener('click', () => {
closeModal(); // only fires for clicks outside modal
});Event Bubbling
Events bubble up — after firing on the target, they fire on the parent, then grandparent, all the way to document. This is how event delegation works: attach one listener to a parent and use e.target to identify the actual clicked child.
// One listener handles all button clicks in the container:
document.querySelector('.btn-group').addEventListener('click', (e) => {
if (e.target.matches('button')) {
console.log('Clicked:', e.target.textContent);
}
});Event Delegation Pattern
Event delegation is the practice of listening on a parent element instead of attaching listeners to every child. It's more efficient and handles dynamically added children automatically.
// Instead of:
list.querySelectorAll('li').forEach(li => li.addEventListener('click', handleClick));
// Use delegation:
list.addEventListener('click', (e) => {
if (e.target.closest('li')) handleClick(e);
});Keyboard Events
Keyboard events fire for key presses. Use e.key (string like 'Enter', 'Escape', 'a') for modern code. Old code used e.keyCode (deprecated). e.metaKey, e.ctrlKey, e.shiftKey detect modifier keys.
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeModal();
if (e.key === 'Enter' && e.ctrlKey) submitForm();
});Removing Event Listeners
Use removeEventListener to detach a listener. The handler must be the same function reference — anonymous functions can't be removed. In React/Vue you typically don't manage this manually.
function handleScroll() { /* ... */ }
window.addEventListener('scroll', handleScroll);
// Later, when done:
window.removeEventListener('scroll', handleScroll);once Option
Pass { once: true } as the third argument to automatically remove the listener after it fires once. Useful for one-time actions like splash screen dismissal.
document.querySelector('#start').addEventListener('click', startApp, { once: true });capture Option
By default, listeners fire during the bubbling phase (up). Pass { capture: true } to fire during the capturing phase (down, before the target's own listeners).
Quick Check
Which method stops the browser from performing its default behaviour for an event?
Recap: DOM Events
addEventListener(type, handler) attaches listeners. The Event object provides target, type, and control methods. preventDefault() blocks defaults. stopPropagation() stops bubbling. Use event delegation for efficiency and dynamic children. Remove listeners to prevent memory leaks.
Frequently asked questions
Is the “addEventListener and Event Object” lesson free?
Yes — the full text of “addEventListener and Event Object” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “addEventListener and Event Object”?
Attach event listeners, receive the Event object, use preventDefault and stopPropagation, and understand event bubbling. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “addEventListener and Event Object” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- querySelector and querySelectorAll
- addEventListener and Event Object
- Changing Content: textContent innerHTML classList
- Creating and Appending Elements