JavaScript Events
JavaScript events are signals that something happened: a click, a key press, a form submit or the page finishing loading. You react to them by attaching a listener function with addEventListener.
Handling a Click
The first argument is the event name, the second is the function to run each time it happens.
const btn = document.createElement("button");
btn.textContent = "Clicked 0 times";
document.body.append(btn);
let clicks = 0;
btn.addEventListener("click", () => {
clicks++;
btn.textContent = `Clicked ${clicks} times`;
});(A button that counts your clicks)
The Event Object
Listeners receive an event object with details: event.target is the element that triggered it, and keyboard events include event.key.
const input = document.createElement("input");
input.placeholder = "Type something";
const out = document.createElement("p");
document.body.append(input, out);
input.addEventListener("input", (e) => {
out.textContent = "You typed: " + e.target.value;
});
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") console.log("Enter pressed");
});(The paragraph mirrors what you type; pressing Enter logs "Enter pressed")
Forms and preventDefault
Submitting a form normally reloads the page. Call event.preventDefault() to handle the data in JavaScript instead. FormData reads all fields at once.
document.body.innerHTML = `
<form>
<input name="email" value="me@example.com">
<button>Subscribe</button>
</form>`;
document.querySelector("form").addEventListener("submit", (e) => {
e.preventDefault();
const data = new FormData(e.target);
console.log("Subscribed:", data.get("email"));
});Subscribed: me@example.com (after clicking Subscribe)
Event Delegation
Events bubble up from the target to its parents. Instead of adding a listener to every item, add one to the parent and check event.target. This also works for items added later.
const ul = document.createElement("ul");
ul.innerHTML = "<li>Tea</li><li>Coffee</li><li>Juice</li>";
document.body.append(ul);
ul.addEventListener("click", (e) => {
const li = e.target.closest("li");
if (li) console.log("You chose", li.textContent);
});You chose Coffee (after clicking Coffee)
Common Events
- click, dblclick: mouse clicks
- input, change: form field values
- submit: form submission
- keydown, keyup: keyboard
- mouseover, mouseout: hover
- DOMContentLoaded: HTML fully parsed
- scroll, resize: window changes
Frequently asked questions
What is the difference between onclick and addEventListener?
onclick holds only one handler and is overwritten by the next assignment. addEventListener can attach many handlers and supports options like once.
How do I remove an event listener?
Call removeEventListener with the same event name and the same function reference. Anonymous functions cannot be removed this way, or use an AbortController signal.
What is event bubbling?
After an event fires on an element, it travels up through its ancestors, triggering their listeners too. e.stopPropagation() stops it.