01 / 21

Event Listeners
in JavaScript

Learn how to make web pages interactive by listening for user actions like clicks, key presses, and form input.

JavaScript

What Is an Event?

An event is any action or occurrence that happens in the browser: a user clicking a button, pressing a key, scrolling the page, or the document finishing loading. JavaScript can detect and respond to these events.

User Events
Clicks, hovers, key presses, form submissions, touch gestures
Browser Events
Page load, resize, scroll, network responses, timers

What Is an Event Listener?

An event listener is a function that waits for a specific event to occur on a specific element. When the event fires, the listener executes a callback function: the code you want to run in response.

Why Event Listeners Matter

Without event listeners, web pages are static. Event listeners turn HTML into interactive applications by connecting user actions to JavaScript logic.

Forms
Validate input before submission
Navigation
Toggle menus, tabs, and modals
Games
Respond to keyboard and mouse input

The Core Syntax

JS
const button = document.querySelector('#myBtn');

button.addEventListener('click', function() {
  alert('Button clicked!');
});

Anatomy of addEventListener

Element .addEventListener() Event Type 'click', 'keydown', ... Callback function(event) { } Event Object e.target, e.type, e.key ...

Common Event Types

Category Event Name Fires When
MouseclickUser clicks an element
MousemouseoverCursor enters an element
KeyboardkeydownA key is pressed
FormsubmitForm is submitted
ForminputInput value changes
WindowloadPage finishes loading

Inline vs addEventListener

Inline Handler
Mixes HTML and JS. Only one handler per event. Hard to maintain. Avoid in modern code.
addEventListener
Multiple handlers per event. Clean separation. Can be removed. Industry standard.
Comparison
// Inline (avoid)
<button onclick="doStuff()">Click</button>

// addEventListener (preferred)
btn.addEventListener('click', doStuff);

The Event Object

Every callback receives an event object automatically. It contains details about what happened: which element was clicked, which key was pressed, where the mouse was, and more.

JS
button.addEventListener('click', function(event) {
  console.log(event.type);     // 'click'
  console.log(event.target);   // the button element
  console.log(event.clientX);  // mouse X position
});

How to Add an Event Listener

1
Select the element using querySelector, getElementById, or similar.
2
Choose the event type: 'click', 'keydown', 'submit', 'input', etc.
3
Write the callback function that runs when the event fires.
4
Call addEventListener on the element with the event type and callback.
5
Test it: trigger the event in the browser and verify the response.

Example 1: Click Counter

HTML + JS
<button id="counter">Clicks: 0</button>

<script>
  let count = 0;
  const btn = document.querySelector('#counter');

  btn.addEventListener('click', function() {
    count++;
    btn.textContent = 'Clicks: ' + count;
  });
</script>

Example 2: Keyboard Input

JS
document.addEventListener('keydown', function(e) {
  if (e.key === 'Enter') {
    console.log('Enter was pressed!');
  }
  if (e.key === 'Escape') {
    console.log('Escape was pressed!');
  }
});

Example 3: Form Validation

JS
const form = document.querySelector('#signupForm');
const email = document.querySelector('#email');

form.addEventListener('submit', function(e) {
  if (!email.value.includes('@')) {
    e.preventDefault();  // stop form
    alert('Enter a valid email!');
  }
});

Removing Event Listeners

Use removeEventListener to detach a handler. To do this, you must pass the exact same function reference that was used to add the listener. This is why you need to use a named function or store your callback in a variable, as new anonymous functions don't have a reusable reference.

JS
function handleClick() {
  console.log('Clicked!');
}

btn.addEventListener('click', handleClick);

// Later, remove it:
btn.removeEventListener('click', handleClick);

Common Mistakes

✕ Calling the Function
Writing addEventListener('click', func()) calls func immediately instead of passing a reference. Omit the parentheses.
✕ Script Before HTML
If your script runs before the element exists in the DOM, querySelector returns null. Place scripts at the end of the body or use DOMContentLoaded.
✕ Typo in Event Name
Writing 'Click' instead of 'click' silently fails. Event names are case-sensitive and always lowercase.

Summary Comparison

Feature Inline onclick addEventListener
Multiple handlers✕ No✓ Yes
Separation of concerns✕ Mixed✓ Clean
Remove handler✕ Messy✓ Easy
Event object accessLess direct✓ Full
Capture/bubble control✕ No✓ Yes

Question 1 of 5

What are the two required arguments of the addEventListener method?

Question 2 of 5

What does e.preventDefault() do inside an event listener?

Question 3 of 5

Which code correctly adds a click listener to a button stored in a variable called myBtn?

Question 4 of 5

Why does removeEventListener require a named function?

Question 5 of 5

A script at the top of the HTML tries to select a button that appears later in the body. What happens and how do you fix it?