A page that never reacts is just a document. Events are how JavaScript hears about clicks, typing, scrolling and much more. By the end of this lesson you will be able to attach listeners, read information from the event, and stop the browser doing something you want to handle yourself.
Events and listeners
An event is the browser telling you something happened. A listener (also called a handler) is a function you register to run when it does. The standard way to register one is addEventListener, which takes the event name and the function:
<button id="counter">Clicked 0 times</button>
<script>
const button = document.getElementById("counter");
let count = 0;
button.addEventListener("click", function () {
count = count + 1;
button.textContent = "Clicked " + count + " times";
});
</script>You can write the handler inline as above, as an arrow function, or as a named function defined elsewhere. Pass the function itself. Writing addEventListener("click", save()) runs save straight away and registers whatever it returned.
You may see older styles such as onclick="..." in the HTML, or button.onclick = fn. They work, but a property holds one handler only, so assigning again replaces the first. addEventListener lets you add as many as you like.
Common event types
| Event | Fires when |
|---|---|
click |
the element is clicked, tapped or activated with the keyboard |
input |
the value of a form field changes, on every edit |
change |
a field's value is committed, often on losing focus |
submit |
a form is submitted |
keydown, keyup |
a key is pressed or released |
mouseover, mouseout |
the pointer enters or leaves |
focus, blur |
an element gains or loses focus |
DOMContentLoaded |
the HTML has been parsed (on document) |
For buttons, use click. It also fires when someone presses Enter or Space on a focused button, so keyboard users are covered. That is one reason to use a real <button> rather than a clickable <div>.
The event object
The browser calls your handler with one argument, the event object. You can name it anything; event, e and evt are common.
<input id="name" placeholder="Type here">
<p id="echo">Nothing typed yet.</p>
<p id="last">Last key: none</p>
<script>
const field = document.getElementById("name");
field.addEventListener("input", function (event) {
document.getElementById("echo").textContent = "You typed: " + event.target.value;
});
field.addEventListener("keydown", function (event) {
document.getElementById("last").textContent = "Last key: " + event.key;
});
</script>Useful properties include:
event.target: the element where the event happened.event.currentTarget: the element the listener is attached to.event.key: for keyboard events, such as"Enter"or"a".event.clientXandevent.clientY: pointer position for mouse events.event.type: the name of the event, such as"click".
Inside a regular function handler, this is the element holding the listener. In an arrow function it is not, so prefer event.currentTarget for clarity.
Preventing default behaviour
Many events have a default action: links navigate, forms submit and reload the page, a right-click opens a menu. Call event.preventDefault() to cancel it.
<a id="link" href="https://example.com/">Visit example.com</a>
<p id="msg"></p>
<script>
document.getElementById("link").addEventListener("click", function (event) {
event.preventDefault();
document.getElementById("msg").textContent = "Link click handled by JavaScript.";
});
</script>Without preventDefault() the browser would leave the page. The same call is how you stop a form from reloading the page, which the forms lesson uses.
Removing a listener
To remove a listener, call removeEventListener with the same function that you added. That means anonymous functions cannot be removed afterwards, so give the handler a name if you will need to.
function sayHi() { console.log("hi"); }
button.addEventListener("click", sayHi);
button.removeEventListener("click", sayHi);You can also pass { once: true } as a third argument so the listener removes itself after running one time:
button.addEventListener("click", sayHi, { once: true });Keyboard shortcuts
A listener on document hears keys no matter what has focus. Here is a tiny example. It reacts when you press the letter h while the preview has focus (click inside the result first).
<p id="status">Press h</p>
<script>
document.addEventListener("keydown", function (event) {
if (event.key === "h") {
document.getElementById("status").textContent = "Hello from the keyboard!";
}
});
</script>Be careful with global shortcuts: do not trigger them while the user is typing in an input, or typing the letter will fire your code.
Common mistakes
- Calling the function by mistake.
addEventListener("click", doIt())runs it immediately. WritedoIt. - Attaching a listener to something that does not exist yet. The selector returned
null, so you get an error. Check the script position. - Listening for
changewhen you wantedinput.changewaits for focus to leave the field. - Trying to remove an anonymous function. Keep a reference to it.
- Using
thisin an arrow function and finding it is not the element. - Making a
<div>clickable with no keyboard support. Use a button. - Adding the same listener in a loop or on each render, so one click triggers many runs.
Exercise
Create a box that is 120 pixels square. Listen to mouseover and mouseout on it to change its colour. Then add a text input and show, below it, how many characters have been typed so far, updating on every input event. Finish with a link that uses preventDefault() and shows the link's href in a paragraph instead of navigating.
Key points
- An event is a signal that something happened, such as a click or a key press; a listener is a function that runs in response.
- addEventListener(type, handler) is the recommended way to attach listeners, and you can add several to one element.
- The handler receives an event object with details such as target, key and clientX.
- preventDefault() stops the browser's default action, for example following a link.
- Pass the function itself to addEventListener, not the result of calling it.