Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 122 ยท CSS and JavaScript in HTML

Event Attributes and Event Listeners

Respond to clicks, typing and other events with HTML event attributes like onclick, learn why addEventListener is better, and use the event object.

Pages become interactive when they respond to things that happen: a click, a key press, a form being submitted, the mouse moving over a picture. Each of these is an event. JavaScript can "listen" for an event and run code when it happens.

HTML offers a quick way to do that, with event attributes such as onclick. You will see them in plenty of older code and in quick demos, so it is worth understanding them. But modern code almost always uses addEventListener() instead. This lesson shows both, explains why the second one wins, and introduces the most useful events and the event object.

Event attributes

An event attribute starts with on, followed by the event name. Its value is a small piece of JavaScript that runs when the event fires:

An onclick attribute

Inside an event attribute, this refers to the element the attribute is on โ€” that is how the second button changes its own label.

Usually the attribute just calls a function defined in a script:

HTML
<button onclick="addToCart()">Add to cart</button>

<script>
  function addToCart() {
    console.log("Added!");
  }
</script>

There is an event attribute for almost every event: onclick, oninput, onchange, onsubmit, onkeydown, onmouseover, onfocus, onload and many more. They are all global attributes, so they work on any element (although an element only receives the events that make sense for it).

Why addEventListener() is better

The same click handler written with addEventListener() looks like this:

addEventListener

It takes a few more lines, but it has clear advantages:

  • HTML stays HTML. The markup describes content; all behavior lives in your scripts, ideally in an external file. That is the same separation you saw with CSS.
  • Several handlers per event. You can call addEventListener("click", โ€ฆ) as many times as you like and every handler runs. An element has only one onclick, and assigning a new one replaces the old one.
  • Removable. removeEventListener() takes a handler off again.
  • Options. A third argument controls details, such as { once: true } to run only the first time.
  • No global functions. Event attributes can only call functions that are visible globally. That doesn't mix well with JavaScript modules, whose functions are private.
  • Security. Sites with a strict Content Security Policy block inline JavaScript, including every onโ€ฆ attribute. addEventListener() in an external file keeps working.

Note the names. The attribute is onclick, but the event passed to addEventListener() is "click" โ€” no on prefix. Writing addEventListener("onclick", โ€ฆ) is a common mistake that fails silently.

You may also see the event handler property form, button.onclick = function () { โ€ฆ };. It lives in JavaScript, which is an improvement, but it still allows only one handler per event. Prefer addEventListener().

Common events

Event Fires whenโ€ฆ Typical elements
click The element is activated by mouse, touch, or Enter/Space on a focused button. Buttons, links, anything.
input The value of a field changes, on every keystroke. <input>, <textarea>, <select>
change A value is committed: a checkbox is ticked, a select changes, a text field loses focus after editing. Form fields.
submit A form is submitted. <form>
keydown / keyup A key is pressed / released. Focused elements, document.
focus / blur An element gains / loses keyboard focus. Links, buttons, fields.
pointerenter / pointerleave A mouse, pen or finger moves over / off the element. Anything.
DOMContentLoaded The HTML has been fully parsed. document
load Everything, including images, has finished loading. window, <img>
Live input

Type in the field: input updates the greeting on every keystroke. Then click outside the field: change fires once, when you have finished editing.

Use real buttons for clickable things. A click listener on a <div> works with a mouse, but a keyboard user can't reach or press that <div>. A <button> is focusable and fires click on Enter and Space automatically. See Keyboard Access and Focus.

The event object

When an event fires, the browser passes your handler an event object full of details about what happened. Name the first parameter of your function (event is the usual choice) to receive it:

  • event.type โ€” the event's name, such as "click".
  • event.target โ€” the element where the event actually happened.
  • event.currentTarget โ€” the element the listener is attached to.
  • event.key โ€” for keyboard events, the key that was pressed, like "Enter" or "a".
  • event.clientX, event.clientY โ€” for pointer events, the position in the window.
  • event.preventDefault() โ€” stops the browser's default action, such as following a link or submitting a form.
The event object

Without preventDefault(), submitting the form would make the browser load a new page. Handling submit this way is a common pattern; you will use it often in the Forms chapter.

Event bubbling and delegation

Most events bubble: after firing on the element you clicked, they travel up through each of its ancestors, all the way to document. That means a single listener on a parent can handle events from all its children. This pattern is called event delegation:

Event delegation

One listener handles all three buttons, and it would also work for buttons added later. event.target tells you which button was clicked, and closest() finds the nearest matching ancestor (or the element itself).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line correctly listens for clicks on a button stored in btn?

    The event name has no on prefix and is a string. Pass the function itself, not the result of calling it.
  2. 2. You attach two click handlers with addEventListener(). What happens on a click?

    addEventListener() adds handlers; it never replaces them. With onclick, the second assignment would replace the first.
  3. 3. Which event fires on every keystroke in a text field?

    input fires whenever the value changes. change waits until the edit is committed, for example when the field loses focus.
  4. 4. In a submit handler, what does event.preventDefault() do?

    It cancels the default action, so your script can handle the data itself.
  5. 5. Why is a click listener on a <div> a poor replacement for a <button>?

    A <button> is focusable and responds to Enter and Space automatically. A plain <div> is neither.

Summary

  • Events are things that happen on the page; handlers are code that responds to them.
  • Event attributes like onclick work, but mix behavior into HTML, allow only one handler and are blocked by strict security policies.
  • addEventListener("click", handler) is the modern approach: several handlers, removable, with options.
  • The event object describes what happened; event.target, event.key and event.preventDefault() are the most used.
  • Events bubble up through ancestors, which makes event delegation possible.

Next lesson: The Document Object Model โ€” finding and changing elements with JavaScript.