Events: making buttons do things
So far your code runs once, top to bottom, and stops. Real pages wait for the user to do something. Every click, key press and scroll fires an event, and you can ask the browser to run a function when one happens:
const button = document.querySelector("#go");
button.addEventListener("click", () => {
console.log("Clicked!");
});
addEventListener takes two things: the event name as a string ("click") and a function to run. That function is called a handler or listener. Notice you pass the function itself; the browser calls it later, every time the event happens, not right now.
Some event names worth knowing: "click", "input" (someone typed in a text box), "keydown", and "mouseover".
A click counter
Put everything from this track together and you get the classic first interactive thing:
let count = 0;
button.addEventListener("click", () => {
count++;
display.textContent = count;
});
Three ideas are working together here. A variable (count) remembers state between clicks. Declaring it with let outside the handler matters: if you put it inside, it would reset to 0 on every click. The handler changes the state, then updates the DOM so the page shows the new value.
That pattern (store the state, change it when something happens, update the page to match) is the core of basically every interactive app, from to-do lists to the apps on your phone. Frameworks like React are mostly fancy ways of doing exactly this.
One more lesson to go: buttons are great, but most real pages also need people to type things in. That is next.
Try it yourself
Edit it. Break it. Run it again.<style>
.big {
font-size: 48px;
}
</style>
<p>Clicks: <span id="count">0</span></p>
<button id="add">Click me</button>
<button id="size">Toggle size</button>
<script>
const display = document.querySelector("#count");
const addButton = document.querySelector("#add");
const sizeButton = document.querySelector("#size");
let count = 0;
addButton.addEventListener("click", () => {
count++;
display.textContent = count;
console.log("count is now", count);
});
sizeButton.addEventListener("click", () => {
display.classList.toggle("big");
});
</script>
Your turn
Type it yourself. That is the whole trick.1Click counter
Make the button work: every click on #add should add 1 to the number shown in #count.
<p>Clicks: <span id="count">0</span></p>
<button id="add">+1</button>
<script>
const display = document.querySelector("#count");
const button = document.querySelector("#add");
let count = 0;
// listen for clicks here
</script>
2Dark mode switch
Right now the button turns dark mode on but can never turn it off. Make each click toggle the class dark on the <body>: on, then off, then on again.
<style>
.dark {
background-color: black;
color: white;
}
</style>
<button id="theme">Dark mode</button>
<script>
const themeButton = document.querySelector("#theme");
themeButton.addEventListener("click", () => {
document.body.classList.add("dark");
});
</script>