An event is something that happens on the page: a click, a key press, a form submission, a finished image load, a resized window. The browser notices it and tells your code, if your code has asked to be told.
The pattern is always the same:
- Pick an element (the target).
- Say which event you care about (
"click"). - Provide a function (the handler or listener) to run when it happens.
<button id="hello">Click me</button>
<p id="out"></p>
<script>
const button = document.querySelector("#hello");
button.addEventListener("click", () => {
document.querySelector("#out").textContent = "You clicked the button!";
});
</script>
Nothing in the script runs when the page loads, apart from setting up the listener. The function runs each time the event happens. This style is called event-driven programming, and it is how almost all interactive pages work.
Common events
| Event | Fires when |
|---|---|
click | an element is clicked (or activated by keyboard) |
input | the value of a field changes as the user types |
change | a field is committed (a menu choice, or leaving a text box) |
submit | a form is submitted |
keydown, keyup | a key is pressed or released |
mouseenter, mouseleave | the pointer enters or leaves |
focus, blur | an element gains or loses focus |
DOMContentLoaded | the HTML has been parsed |
scroll, resize | the page scrolls or the window changes size |
Events happen in the browser, not in the language
Events are part of the DOM and Web APIs. They are how the browser talks to your JavaScript.
What you can do in a handler
Anything: change text, toggle classes, read inputs, call functions, start a timer, send a request.
<button id="like">♡ Like</button>
<script>
let liked = false;
const button = document.querySelector("#like");
button.addEventListener("click", () => {
liked = !liked;
button.textContent = liked ? "♥ Liked" : "♡ Like";
});
</script>
Use real buttons
Use a <button> (or a link) for things that are clicked. A button works with the mouse, keyboard and screen readers automatically. A <div> with a click listener does not. See Accessible Buttons and ARIA.