JavaScript in the page · Lesson 31 of 45
Events
Make the page react when someone clicks or types.
el.addEventListener("click", fn) tells the browser: “when this event happens on this element, run this function.” The function receives an event object with details: e.target (the element), e.key (the key pressed).
| Event | Fires when |
|---|---|
| you click |
| a field changes (every keystroke) |
| a field's change is committed |
| a form is submitted |
| a key is pressed |
| the pointer enters/leaves |
<button id="btn">Clicked 0 times</button>
<p><input id="name" placeholder="Type your name"></p>
<p id="hello"></p>
<script>
let count = 0
const btn = document.querySelector("#btn")
btn.addEventListener("click", () => {
count++
btn.textContent = `Clicked ${count} times`
})
document.querySelector("#name").addEventListener("input", (e) => {
document.querySelector("#hello").textContent = "Hi " + e.target.value
})
document.addEventListener("keydown", (e) => console.log("key:", e.key))
</script>Click the button, type in the box, and watch the console.
Event delegation
Events travel up the tree (bubbling): a click on an li also reaches its ul. So instead of a listener per item, put one on the parent and inspect e.target. It even works for items added later.
<ul id="menu">
<li data-page="home">Home</li>
<li data-page="courses">Courses</li>
<li data-page="about">About</li>
</ul>
<script>
document.querySelector("#menu").addEventListener("click", (e) => {
const li = e.target.closest("li")
if (li) console.log("Go to", li.dataset.page)
})
</script>Order the lines
Order it so clicking the button logs clicked.
- Click the lines in the right order
Quick question
Which event fires on every character typed into a field?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.