Handling events
โ Report an issue with this lessonconst button = document.querySelector("#submit-btn");
button.addEventListener("click", (event) => {
console.log("Clicked!", event.target);
});
For forms, prevent the page's default full reload so you can handle submission with JavaScript:
const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
event.preventDefault();
const email = form.querySelector("#email").value;
console.log("Submitted:", email);
});
Common events: click, submit,
input (fires on every keystroke), change (fires
when a field loses focus after changing).
The event object your handler receives carries useful
details beyond just "something happened":
event.targetโ the exact element the event originated from.event.keyโ on keyboard events, which key was pressed (e.g."Enter","Escape").event.preventDefault()โ stops the browser's default behavior for that event (a form reloading the page, a link navigating away).event.stopPropagation()โ stops the event from bubbling up to parent elements, which matters once you're using event delegation (covered later in this course).
A common mistake is attaching a listener before the element exists in
the page yet โ for example, running your script in the
<head> before the body has loaded, so
document.querySelector returns null and calling
.addEventListener on it throws. Either place your
<script> tag at the end of <body>,
or wrap your setup code in a DOMContentLoaded listener:
document.addEventListener("DOMContentLoaded", () => {
document.querySelector("#submit-btn").addEventListener("click", handleClick);
});
Another one: writing button.addEventListener("click", handleClick())
with parentheses calls handleClick immediately and passes its
return value as the listener โ almost never what you want. Pass
the function itself, not the result of calling it:
button.addEventListener("click", handleClick).
Try it yourself
Submitted: ada@example.com
Run your code and get it working before marking this lesson complete.
8 more lessons โ including Project: build a live search box โ plus a certificate are waiting.
Unlock the full course โ $59.99