Events are how your web page reacts to user input or system occurrences. Examples include mouse clicks, key presses, page load, and form submission.
Here are some common event types:
click – mouse clickmouseover / mouseout – hover in and outkeydown, keyup – keyboard inputload – when the page finishes loadingsubmit – when a form is submittedinput, change – user input changesThis older approach embeds the handler directly in HTML. It's quick but not recommended for scalability.
<button onclick="alert('Clicked!')">Click me</button>The modern and cleaner way to bind events:
const btn = document.querySelector("button");
btn.addEventListener("click", function() {
alert("Clicked!");
});You can add multiple listeners to the same element and separate logic from HTML.
Event handlers receive an object with information about the event:
document.addEventListener("keydown", function(event) {
console.log("Key:", event.key);
console.log("Code:", event.code);
});This object gives access to things like event.target, event.type, and modifier keys.
function greet() {
console.log("Hello");
}
btn.addEventListener("click", greet);
btn.removeEventListener("click", greet);Only named functions can be removed. Anonymous ones can't be unregistered this way.
addEventListener over inline handlersAsk the AI if you need help understanding or want to dive deeper in any topic