Think of a "Pay" button on a cart page. You don't know when someone will click it: one second after the page opens, five minutes later, or never. So your code has to wait, and run at the moment the button is clicked.
That click is called an event. An event is something that happens on the page, such as a button being clicked, a letter being typed, or a form being sent. JavaScript can wait for an event, then run a function at the moment the event happens. You do this with addEventListener, which means "attach a listener".
Attach a listener to a button
The page has <button>Click Me</button>. The code below attaches a listener to that button:
const button = document.querySelector("button");
button.addEventListener("click", (e) => {
console.log("click:", e.target.textContent);
});
document.querySelector("button")finds the button on the page. It is stored in the variablebutton.addEventListeneris called on the element you want to listen to, herebutton. Its first argument,"click", is the name of the event to wait for.- Its second argument,
(e) => { ... }, is the function that runs every time that event happens. This function is called a listener. eis the event object: an object that holds information about the event. The browser passes it to the listener.e.targetis the element where the event happened, here the button, andtextContentis that button's text.
When the page loads, the console is still empty. When you click the button, the console prints click: Click Me. Click again and the line is printed again. So the listener does not run when the page loads. It waits until the button is clicked.
Change the page inside the listener
Now the page has one button and one paragraph: <p id="message">Not paid yet</p>. The code below replaces the paragraph's text when the button is clicked:
const button = document.querySelector("button");
const message = document.querySelector("#message");
button.addEventListener("click", () => {
message.textContent = "Paid";
});
Before the click, the paragraph still says Not paid yet. After the click, it says Paid.
The rule: code outside the listener runs once, when the page loads. Code inside the listener runs later, every time the event happens. If the line message.textContent = "Paid" is placed outside the listener, the paragraph's text has already changed to Paid before anyone clicks.
Read typing with the input event
This page has one text field and one empty paragraph. The code below writes a greeting in that paragraph, following what you type:
const input = document.querySelector("input");
const greeting = document.querySelector("#greeting");
input.addEventListener("input", () => {
greeting.textContent = "Hello, " + input.value;
});
- The
"input"event happens every time the field's content changes, so once for each letter you type. input.valueis what the field holds at that moment. The listener reads it every time it runs, so the value is always the latest one. If the listener takese,e.target.valuegives the same value."input"in quote marks is the event's name.inputwithout quote marks is the variable that holds the field.
If you type Ani, the paragraph changes three times: Hello, A, then Hello, An, then Hello, Ani. There is also a "change" event, which happens only once: when you finish typing and click outside the field.
Other events, and cancelling the default action
Event names are written in lowercase, without on in front: "click" (clicked), "input" (typed into), "change" (finished changing), "submit" (form sent), "keydown" (a keyboard key pressed).
Some events have a default action: something the browser does by itself when the event happens. For example, when a form is sent, the browser reloads the page. e.preventDefault() cancels that default action:
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("Sent, and the page did not reload");
});
When the form is sent, the page does not reload, and the message is printed in the console.
Removing a listener
removeEventListener removes a listener. It needs the exact same function that was attached, so give the function a name first:
const button = document.querySelector("button");
function greet() {
console.log("Hello!");
}
button.addEventListener("click", greet);
button.removeEventListener("click", greet);
greet is written without (), because you pass the function itself, not the result of running it. After the last line the listener is removed, so a click on the button prints nothing.
A function without a name, () => { ... }, can't be removed this way. If you write the same body again in removeEventListener, JavaScript treats it as a new function, not the one you attached.
⚠️ Listeners that stay silent, or run too early
- Changing the text outside the listener. The text changes when the page loads, not when the button is clicked. Move that line inside the listener's
{ }. - Writing
()after the function's name.addEventListener("click", greet())runsgreetright away, before any click. Write onlygreet. - A wrong event name. There is no event named
"onclick"or"Click", so the listener never runs. Write"click". onclickholds only one function. You can also attach a functionfnwithbutton.onclick = fn. But a second function set this way replaces the first one. WithaddEventListener, one element can have many listeners.
TL;DR: An event is something that happens on the page, such as a button being clicked. element.addEventListener("click", fn) attaches a listener: a function that runs every time that event happens, not when the page loads. So put changes to the page inside the listener. The "input" event happens every time a text field's content changes. You read the content from input.value, where input is a variable that holds the field. e.preventDefault() cancels the browser's default action, such as reloading the page when a form is sent (e is the event object the listener receives). removeEventListener removes a listener, and it needs the exact same function that was attached.
⚡ A listener waits for the event
Write:
button.addEventListener("click", () => {
message.textContent = "Paid";
});
Guess first: button is a button on the page, message a paragraph. The listener (the function attached to the button) runs when the button is clicked. If the line message.textContent = "Paid" is placed outside the listener, when does the paragraph's text change?
When the page loads, before anyone clicks. Code outside the listener runs once, when the page loads.
Meaning: An event is something that happens on the page, such as a click. The first argument of addEventListener is the event's name, in lowercase without on. The second argument is the listener: the function that runs every time that event happens.
⚡ Read typing with input
Write:
input.addEventListener("input", () => {
greeting.textContent = "Hello, " + input.value;
});
Meaning: input without quote marks is a variable that holds a text field, and greeting is a paragraph. The "input" event happens every time that field's content changes, once for each letter. input.value is what the field holds at that moment. The listener reads it every time it runs, so the value is always the latest one.
⚡ Removing needs the same function
Write:
function greet() {
console.log("Hello!");
}
button.addEventListener("click", greet);
button.removeEventListener("click", greet);
Guess first: removeEventListener removes the listener greet. If the listener is a function without a name, can you remove it by writing the function's body again?
No. A function you write again is a new function, even when its body is the same. removeEventListener needs the exact same function that was attached.
Meaning: removeEventListener removes a listener and needs the exact same function, so give the function a name first. greet is written without (), because you pass the function itself, not the result of running it.