22. JavaScript Events

What you will learn

  • What events are
  • How to listen with addEventListener
  • The event object
  • Event delegation and keyboard events

What is an event?

An event is something that happens on the page: a click, a key press, a form submission, the page finishing loading. JavaScript can listen for events and run a function in response.

Common events

Event Happens when
click An element is clicked or activated by keyboard
input The value of a field changes as the visitor types
change A field’s value is committed (for example a select changes)
submit A form is submitted
keydown A key is pressed
mouseover, mouseout The pointer enters or leaves
focus, blur An element gains or loses focus
DOMContentLoaded The page structure is ready

addEventListener

Syntax

element.addEventListener("event", function () {
  // code to run
});

Example

<button id="btn" type="button">Click me</button>
<p id="demo">Waiting...</p>

<script>
  const btn = document.getElementById("btn");

  btn.addEventListener("click", function () {
    document.getElementById("demo").textContent = "Button was clicked!";
  });
</script>

Output (before clicking; run it in the editor)

Waiting…

You can add several listeners for the same event on one element. Use real <button> elements for clickable things, so keyboard users can use them too.

The event object

The browser passes an event object to your function with details about what happened.

Example

<input id="field" type="text" placeholder="Type here">
<p id="demo"></p>

<script>
  document.getElementById("field").addEventListener("input", function (event) {
    const length = event.target.value.length;
    document.getElementById("demo").textContent = "Characters typed: " + length;
  });
</script>

Output (run it in the editor)

event.target is the element that triggered the event. Other useful items are event.key (the key pressed) and event.preventDefault() (stop the browser’s normal action).

Keyboard events

Example

<p>Click in the box, then press a key.</p>
<input id="keys" type="text">
<p id="demo"></p>

<script>
  document.getElementById("keys").addEventListener("keydown", function (event) {
    document.getElementById("demo").textContent = "You pressed: " + event.key;
  });
</script>

Output (run it in the editor)

Click in the box, then press a key.

Preventing the default action

Some elements have built-in behaviour, such as a link navigating or a form submitting. preventDefault() stops it so your code can take over.

Example

<a id="link" href="https://example.com">A link that does not navigate</a>
<p id="demo"></p>

<script>
  document.getElementById("link").addEventListener("click", function (event) {
    event.preventDefault();
    document.getElementById("demo").textContent = "Navigation stopped.";
  });
</script>

Event delegation

Instead of adding a listener to every item in a list, add one to the parent. Events bubble up from the clicked element, and event.target tells you which item it was. It also works for items added later.

Example

<ul id="menu">
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>
<p id="demo">Click an item.</p>

<script>
  document.getElementById("menu").addEventListener("click", function (event) {
    const item = event.target.closest("li");
    if (item) {
      document.getElementById("demo").textContent = "You chose: " + item.textContent;
    }
  });
</script>

Output (run it in the editor)

  • Home
  • About
  • Contact

Click an item.

Removing a listener

Use a named function so you can remove it later with removeEventListener. An anonymous function cannot be removed. The { once: true } option makes a listener run only one time.

Syntax

button.addEventListener("click", sayHi, { once: true });

Common mistakes

  • Writing addEventListener("click", myFunction()) with brackets, which runs it immediately.
  • Using "onclick" as the event name. The name is "click".
  • Adding a listener before the element exists.
  • Making a clickable <div> that keyboard users cannot reach. Use a button.
  • Listening on hundreds of items instead of delegating.

Exercise

As the visitor types in the field, update the paragraph to say Hello, followed by what they typed. Use textContent.

Show solution
<input id="name" type="text" placeholder="Your name">
<p id="demo">Hello!</p>

<script>
  document.getElementById("name").addEventListener("input", function (event) {
    document.getElementById("demo").textContent = "Hello, " + event.target.value;
  });
</script>

Knowledge check

1. Which method attaches a listener?

addEventListener()

2. What does event.preventDefault() do?

It stops the browser’s normal action, such as following a link or submitting a form.

3. What is event delegation?

One listener on a parent handles events from its children, using event.target.

Summary

  • Events let your code react to the visitor.
  • The event object tells you what happened and which element it happened to.
  • Delegate to a parent for lists, and use real buttons for accessibility.
Scroll to Top