JavaScriptintermediate 8 min
React to clicks, key presses and form input with addEventListener.
How to run code when the user clicks, types or submits, and how to read information from the event.
Pages are only interactive because code responds to events. Buttons, menus, games and forms all depend on them.
An event is something that happens on the page. You attach an event listener, a function that runs when it happens:
The listener receives an event object with details:
event.target is the element that triggered it.event.key is the key pressed, in keyboard events.event.preventDefault() stops the browser's default action, such as a form reloading the page.Common events: click, input (every change in a text field), change, submit, keydown, mouseenter.
Event delegation: instead of adding a listener to every list item, add one to the parent and check event.target. It works even for items added later.
count lives outside the listener so it remembers its value between clicks.input listener fires on every keystroke. event.target.value is the current text, shown in the greeting.<ul> handles clicks on any <li>. We check event.target.tagName and strike the clicked item through.Click the button, type in the box and click list items in the preview. Then add a reset button that sets count back to 0.
addEventListener("click", doIt()) runs it immediately. Write doIt or () => doIt().preventDefault() on form submit, so the page reloads.addEventListener(type, fn) runs code when something happens.Next: code that waits, with async and await.
button.addEventListener("click", () => {
console.log("clicked");
});<button id="btn">Clicked 0 times</button>
<input id="name" placeholder="Type your name">
<p id="greeting"></p>
<ul id="list"><li>One</li><li>Two</li><li>Three</li></ul>
<script>
let count = 0;
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
count++;
btn.textContent = "Clicked " + count + " times";
});
document.querySelector("#name").addEventListener("input", (event) => {
document.querySelector("#greeting").textContent = "Hello, " + event.target.value;
});
document.querySelector("#list").addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
event.target.style.textDecoration = "line-through";
}
});
</script>