An Event is anything that happens on the page: a click, a keypress, a window resize, or even a mouse hover. An EventListener is a function that sits and "waits" for that specific event to happen, then runs a block of code.
1. addEventListener()
This is the modern way to handle interaction. It takes two main arguments:
The Type: What are we listening for? (
"click","submit","keydown", etc.)The Callback: What function should run when it happens?
2. The Event Object (e)
When an event happens, JavaScript automatically passes an "event object" to your function. It contains useful info, like which key was pressed or the coordinates of a mouse click.
The Code Example
Imagine you have a button in HTML: <button id="loginBtn">Login</button>
// 1. Select the element first
const loginBtn = document.querySelector("#loginBtn");
// 2. Attach the Listener
loginBtn.addEventListener("click", function(event) {
// 'event' (or 'e') contains info about the click
console.log("Button clicked at coordinates:", event.clientX, event.clientY);
// Change the button text when clicked
loginBtn.innerText = "Processing...";
loginBtn.style.backgroundColor = "#ccc";
});
// 3. Listening for Keyboard Events
document.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
console.log("User pressed the Enter key!");
}
});
// 4. Preventing Default Behavior
// Useful for forms so the page doesn't refresh on submit
const myForm = document.querySelector("#userForm");
myForm.addEventListener("submit", (e) => {
e.preventDefault(); // Stops the page reload
console.log("Form submitted safely via JS!");
});