JavaScript · The DOM

Events

Events are how the page tells your code “something happened” — a click, a key press, a form submission.

Intermediate 5 min Lesson 27 of 49 Runnable examples
Before you start:DOM Manipulation
0/49 in JavaScript
On this page · 5 min · Intermediate

Learning objectives#

  • Listen for events with addEventListener
  • Use the event object (target, key)
  • Handle input, keyboard and form events
  • Stop default browser behaviour with preventDefault

Explanation#

element.addEventListener('click', handler) runs handler every time the event happens.

The handler receives an event object with details: e.target (the element), e.key (for keyboard events), and more.

Common events: click, input (every keystroke), change, keydown, submit, mouseover, scroll.

e.preventDefault() stops the browser’s default action — for example, stopping a form from reloading the page.

Code example: Reacting to the user#

HTMLReacting to the user Runnable
<input id="name" placeholder="Type your name">
<p id="hello">Hello!</p>
<button id="count">Clicked 0 times</button>
<form id="form"><button>Submit</button></form>


<script>
  const hello = document.querySelector('#hello');
  document.querySelector('#name').addEventListener('input', (e) => {
    hello.textContent = `Hello, ${e.target.value || 'stranger'}!`;
  });


  let clicks = 0;
  const btn = document.querySelector('#count');
  btn.addEventListener('click', () => {
    clicks++;
    btn.textContent = `Clicked ${clicks} times`;
  });


  document.addEventListener('keydown', (e) => console.log('Key pressed:', e.key));


  document.querySelector('#form').addEventListener('submit', (e) => {
    e.preventDefault();
    console.log('Form submit stopped — no page reload');
  });
</script>
Expected output
Typing updates the greeting live; the button counts clicks; key presses are logged; submitting the form logs a message instead of reloading.
Opens this example in the full playground

Step-by-step explanation#

  1. The input event fires on every keystroke; e.target.value is the current text.
  2. The click handler updates a counter stored in a variable.
  3. A keydown listener on document logs every key.
  4. preventDefault stops the form’s normal page reload so JavaScript can handle it.

Real-world use case#

Live search boxes, “like” buttons, keyboard shortcuts (Ctrl+K) and AJAX form submissions all use event listeners.

Common mistakes#

Calling the handler instead of passing it

btn.addEventListener('click', save()) runs save immediately. Pass save without parentheses.

Forgetting preventDefault on forms

Without it, the browser reloads the page and your JavaScript result disappears.

Best practices#

  • Use addEventListener rather than onclick attributes
  • Use input for live updates and change for final values
  • Use event delegation for long or dynamic lists
  • Remove listeners you no longer need

Remember this#

addEventListener(what, whatToDo).

e.target = the element that triggered the event.

preventDefault = “browser, don’t do your usual thing”.

Practice exercise#

Your task: Make a character counter: show “12 / 100” under a textarea as the user types.

Show solution
HTML Runnable
<textarea id="t" maxlength="100"></textarea>
<p id="c">0 / 100</p>
<script>
  document.querySelector('#t').addEventListener('input', e => {
    document.querySelector('#c').textContent = `${e.target.value.length} / 100`;
  });
</script>
Opens this example in the full playground

Mini quiz#

Events quizMultiple choice Question 1 of 1

Which event fires on every keystroke in a text input?

Score so far: 0/0

Want more? Practise all JavaScript MCQs · JavaScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.