JavaScript Events
Interactivity on the web is driven by Events. An event is simply a signal triggered by the browser that something has happened—a user clicked a button, scrolled, typed into an input, or the page finished loading.
We write "Event Listeners" to wait for these triggers and run functions concurrently.
Adding Event Listeners
The most modern and robust method for handling events is addEventListener().
<button id="myBtn">Click Me!</button>
const btn = document.getElementById("myBtn");
// Syntax: element.addEventListener("event_type", callbackFunction);
btn.addEventListener("click", () => {
console.log("Button was clicked!");
document.body.style.backgroundColor = "red";
});
// You can easily attach multiple listeners to the exact same element!
btn.addEventListener("dblclick", () => {
console.log("Button double clicked!");
});
The Event Object
When an event triggers your callback function, the browser automatically passes an Event Object as the first argument to your function. It contains rich data about the interaction.
const input = document.querySelector("input");
input.addEventListener("keydown", (event) => {
// We can see exactly what key the user pressed string-by-string
console.log(`User pressed the key: ${event.key}`);
// Check if they hit Enter!
if (event.key === "Enter") {
console.log("Form Submitted!");
}
});
Form Submissions and Prevent Default
When hooking into HTML <form> submissions, the browser's default behavior is to hard-refresh the page to send the data. We use event.preventDefault() to stop this refresh, allowing JavaScript to handle the logic seamlessly.
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault(); // HALT the page refresh!
// Now we can process the form softly
console.log("Form intercepted via JS");
});