An event is something that happens on the page: a click, a key press, typing in a box, submitting a form or the page finishing loading. JavaScript can listen for an event and run a function when it occurs. Menus, sliders, live search boxes and browser games are all built on this idea, and addEventListener() is the method that wires an event to your code.
In this lesson you will learn
- Attaching handlers with
addEventListener() - Using the event object and
event.target - Common events: click, input, submit, keydown
- Stopping default behaviour with
preventDefault() - Event delegation for lists that change
Click and Input Events
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Events</title>
<style>
body { font-family: sans-serif; }
button { padding: 6px 14px; }
#out { margin-top: 8px; color: #00695c; }
</style>
</head>
<body>
<button id="plus">+1</button>
<button id="reset">Reset</button>
<span id="count">0</span>
<p><input id="name" placeholder="Type your name"></p>
<p id="out">Waiting for input...</p>
<script>
let count = 0;
const countEl = document.getElementById("count");
document.getElementById("plus").addEventListener("click", () => {
count++;
countEl.textContent = count;
});
document.getElementById("reset").addEventListener("click", () => {
count = 0;
countEl.textContent = count;
});
document.getElementById("name").addEventListener("input", (event) => {
const value = event.target.value.trim();
document.getElementById("out").textContent =
value ? "Hello, " + value + "! (" + value.length + " letters)" : "Waiting for input...";
});
</script>
</body>
</html>
Result
element.addEventListener("click", handler)runshandlerevery time the element is clicked. Try the buttons in the preview.- The handler receives an event object describing what happened.
event.targetis the element that triggered it, soevent.target.valueis the text in the input. - The
inputevent fires on every change to a text field, which makes live previews and character counters simple. Thechangeevent fires only when the field loses focus. - The counter’s value lives in a variable,
count; the page just displays it. Keeping data in variables and updating the DOM from them is a good habit.
Forms, preventDefault and Delegation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form and delegation</title>
<style>
body { font-family: sans-serif; }
li { cursor: pointer; padding: 2px 0; }
.error { color: crimson; }
</style>
</head>
<body>
<form id="todo-form">
<input id="task" placeholder="New task">
<button type="submit">Add</button>
<span id="error" class="error"></span>
</form>
<ul id="tasks"><li>Click a task to remove it</li></ul>
<script>
const form = document.getElementById("todo-form");
const input = document.getElementById("task");
const tasks = document.getElementById("tasks");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the page from reloading
const text = input.value.trim();
if (text === "") {
document.getElementById("error").textContent = "Please type a task.";
return;
}
document.getElementById("error").textContent = "";
const li = document.createElement("li");
li.textContent = text;
tasks.appendChild(li);
input.value = "";
input.focus();
});
// One listener on the list handles every item, even new ones
tasks.addEventListener("click", (event) => {
if (event.target.tagName === "LI") event.target.remove();
});
</script>
</body>
</html>
Result
- Listen for
submiton the form, notclickon the button. That way pressing Enter also works. - A form normally reloads the page when submitted.
event.preventDefault()stops that so JavaScript can handle the data. It also stops links from navigating. - The code checks for an empty value and shows a message before adding anything. That is basic client-side validation.
- Event delegation: instead of adding a listener to every
<li>, one listener on the<ul>handles them all. Clicks bubble up from the clicked item to its parents, andevent.targettells you which item was clicked. New items work automatically.
Common Events
| Event | Fires when |
|---|---|
click, dblclick | An element is clicked or double-clicked |
input | The value of a field changes, on each keystroke |
change | A select, checkbox or field value is committed |
submit | A form is submitted |
keydown, keyup | A key is pressed or released; event.key says which |
mouseenter, mouseleave | The pointer moves onto or off an element |
focus, blur | An element gains or loses focus |
DOMContentLoaded | The HTML has been fully read (on document) |
Common Mistakes
- Calling the handler instead of passing it:
addEventListener("click", save()). Writesavewithout parentheses. - Forgetting
preventDefault()on a form, so the page reloads and your changes vanish. - Using inline
onclick="..."attributes, which mix code into HTML and allow only one handler. PreferaddEventListener. - Adding listeners inside a loop that runs repeatedly, so one click triggers the handler several times.
Practice Exercises
Exercise 1. Make a button with id theme toggle a dark class on the body.
Show answer
document.getElementById("theme").addEventListener("click", () => {
document.body.classList.toggle("dark");
});
Exercise 2. Log the name of every key the user presses on the page.
Show answer
document.addEventListener("keydown", (event) => {
console.log("Pressed:", event.key);
});
Frequently Asked Questions
How do I remove an event listener?
Call removeEventListener with the same event name and the same function reference. This only works if the handler was a named function or stored in a variable, not an inline arrow function.
What is the difference between event.target and event.currentTarget?
event.target is the element where the event started, such as the clicked list item. event.currentTarget is the element the listener is attached to, such as the list.
Summary
addEventListener(type, handler)runs code when something happens.- The event object describes the event;
event.targetis where it started. - Use
submitwithpreventDefault()for forms. - Events bubble, so one listener on a parent can handle many children.
Next: JavaScript Strings.
