Events
Responding to clicks.
Interactive pages respond to people. A click, a key press, typing in a box. Each of those is an event. You listen for an event with add event listener, and give it a function to run.

- Clicks, keys, typing
- Each is an event
- addEventListener
A click counter
We find the button and the paragraph. Add event listener says, when this button is clicked, run this function. The function adds one to the count, and updates the text. The screenshot was taken after clicking the button three times.
<link rel="stylesheet" href="style.css">
<h1>Clicks</h1>
<button id="btn">Click me</button>
<p id="out" class="big">0</p>
<script>
const btn = document.querySelector("#btn");
const out = document.querySelector("#out");
let count = 0;
btn.addEventListener("click", () => {
count++;
out.textContent = count;
});
</script>Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#btn", "times": 3}]Common events
Click fires when something is clicked. Input fires every time the text in a box changes. Submit fires when a form is sent. Key down fires when a key is pressed. And DOM content loaded fires when the page's HTML is ready.
| key | value |
|---|---|
| click | pressed |
| input | text changed |
| submit | form sent |
| keydown | key pressed |
Summary
Add event listener runs a function whenever an event happens, like a click. Next, the event object, and what it tells you.
Key takeaways- addEventListener(type, fn)
- click, input, submit
- Update the page