Beginner25 min read

Events & Interactivity

Make your web pages interactive by handling user events like clicks, keyboard input, and form submissions.

What Are Events?

Events are things that happen in the browser — a user clicks a button, types in a text field, moves the mouse, submits a form, or the page finishes loading. JavaScript uses an event-driven programming model, meaning your code waits for events to occur and then responds to them.

Here are some common events you will work with:

EventWhen it fires
clickUser clicks an element
dblclickUser double-clicks an element
mouseoverMouse pointer enters an element
mouseoutMouse pointer leaves an element
keydownUser presses a key
keyupUser releases a key
inputValue of an input element changes
submitA form is submitted
loadThe page (or an image) finishes loading
scrollThe user scrolls the page

The flow works like this:

  1. Something happens in the browser (the user clicks a button).
  2. The browser creates an event object describing what happened.
  3. If your code has registered a listener for that event on that element, your callback function runs.

This is what makes web pages interactive — instead of running all your code at once, you set up listeners that respond when the user takes action.

Adding Event Listeners

The standard way to listen for events is with addEventListener():

javascript
const button = document.querySelector('#myButton');

button.addEventListener('click', function() {
  console.log('Button was clicked!');
});

The method takes two required arguments:

  1. Event type — a string like 'click', 'input', 'keydown', etc.
  2. Callback function — the function to run when the event occurs.

You can also pass a named function:

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

button.addEventListener('click', handleClick);

Removing a listener requires a reference to the same function:

javascript
button.removeEventListener('click', handleClick);

This is why named functions are useful — you cannot remove an anonymous function because you have no reference to pass to removeEventListener.

Why addEventListener is better than onclick:

You might see older code using HTML attributes like onclick or property assignment:

html
<!-- HTML attribute — avoid this -->
<button onclick="alert('hi')">Click</button>
javascript
// Property assignment — only allows one handler
button.onclick = function() { console.log('clicked'); };

The problem with these approaches:

  • HTML attributes mix JavaScript into HTML, making code harder to maintain.
  • Property assignment only allows one handler per event. If you set onclick twice, the first handler is lost.
  • addEventListener allows multiple handlers for the same event and provides more control (like capturing vs bubbling).

Always use addEventListener in modern JavaScript.

The Event Object

When an event fires, the browser passes an event object to your callback function. This object contains information about what happened:

javascript
button.addEventListener('click', function(event) {
  console.log(event.type);   // 'click'
  console.log(event.target); // the element that was clicked
});

Useful properties and methods of the event object:

  • event.target — the element that triggered the event (the element the user actually clicked, typed in, etc.).
  • event.currentTarget — the element the listener is attached to (same as this in regular functions).
  • event.type — the event type as a string ('click', 'keydown', etc.).

event.preventDefault() stops the browser's default behavior for an event:

javascript
const form = document.querySelector('form');

form.addEventListener('submit', function(event) {
  event.preventDefault(); // Stop the form from submitting and reloading the page
  console.log('Form data processed by JavaScript instead');
});

const link = document.querySelector('a');
link.addEventListener('click', function(event) {
  event.preventDefault(); // Stop the link from navigating
  console.log('Navigation prevented');
});

event.stopPropagation() prevents the event from bubbling up to parent elements. This is related to event delegation, a powerful pattern where you add a single listener to a parent element instead of one to each child:

javascript
const list = document.querySelector('ul');

list.addEventListener('click', function(event) {
  if (event.target.tagName === 'LI') {
    console.log('Clicked:', event.target.textContent);
  }
});

Event delegation is efficient because you only need one listener regardless of how many list items exist — even items added dynamically after the listener is attached will be handled.

A Click Counter

html
<button id="btn">Click me!</button>
<p>You clicked <span id="count">0</span> times.</p>

<script>
  let count = 0;
  const btn = document.getElementById('btn');
  const display = document.getElementById('count');

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

What method prevents a form from submitting and reloading the page?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.