Last updated
JavaScript Events
Definition: An event is something that happens on a page — a click, a key press, the page loading. JavaScript can "listen" for an event and run a function in response. This is what makes pages interactive.
Example 1 — the idea (addEventListener)
In a real page you connect an event to a function like this:
// In a real web page:
button.addEventListener("click", function() {
console.log("Button was clicked!");
});
Common events
click— the user clicks somethinginput/change— a field is typed in or changedsubmit— a form is submittedmouseover— the pointer enters an elementkeydown— a key is pressed
Example 2 — a handler function
The function that runs for an event is just a normal function. We can call it directly here to show the idea:
function handleClick() {
console.log("Pretend a button was clicked");
}
handleClick();
Example 3 — passing event info
function onKey(key) {
console.log("You pressed: " + key);
}
onKey("Enter");
onKey("a");
💡 Next step: events are where JavaScript becomes powerful — connecting your code to real things users do on a page.
Try it Yourself
Output
Ad · responsive