When the browser runs your callback, it passes in a special object with information about what just happened. It's called the event object, and it's usually named event or just e:
button.addEventListener("click", (event) => {
console.log(event.type); // "click"
console.log(event.target); // the element that was clicked
});
The most useful property is event.target: the element where the event happened. There are also properties specific to each kind of event. For keyboard events, event.key tells you which key was pressed:
document.addEventListener("keydown", (event) => {
console.log(`You pressed: ${event.key}`);
if (event.key === "Enter") {
console.log("Enter! Submitting...");
}
if (event.key === "ArrowUp") {
console.log("Moving up! ⬆️");
}
});
We attached this listener to the whole document, so it catches key presses anywhere on the page. Try pressing letters, numbers, arrow keys and Enter, and watch the console. This is how browser games handle keyboard controls!
For mouse events, event.clientX and event.clientY tell you exactly where the mouse pointer was on the screen, in pixels.