JS Events
An event is something that happens on the page — a click, a key press, a load, a network response. JavaScript reacts with event listeners.
Three ways to listen
| Approach | Example | When to use |
|---|---|---|
| Inline attribute | <button onclick="…"> | Quick demos only. Mixes structure + behaviour. |
| Property assignment | el.onclick = fn | Simple — but you can only attach one handler. |
addEventListener | el.addEventListener("click", fn) | The right answer for real apps. Multiple listeners, options. |
The most-used events
| Event | Fires when… |
|---|---|
click | Mouse click or touch tap. |
input | Form field value changes — every keystroke. |
change | Field commits a change (e.g. blur on text, selection on select). |
submit | Form is submitted. Use e.preventDefault() to handle in JS. |
keydown / keyup | Key pressed / released. |
scroll | Element scrolled. Throttle for performance. |
load / DOMContentLoaded | Page assets fully loaded / DOM is parsed. |
mouseenter / mouseleave | Pointer enters / leaves the element. |
The event object
JS
document.querySelector("form").addEventListener("submit", (e) => {
e.preventDefault(); // don't let the browser do the default
console.log(e.target); // the form element
console.log(e.type); // "submit"
const data = new FormData(e.target);
console.log([...data]);
});
Event delegation
Listen on the parent for events that bubble up from children — efficient and handles dynamically-added children for free.
JS
document.querySelector("#todo-list").addEventListener("click", (e) => {
if (e.target.matches("[data-delete]")) {
e.target.closest("li").remove();
}
});
Tip: Remove listeners with
removeEventListener using the same function reference. Anonymous arrow functions can't be removed — store the function in a variable if you'll need to detach it.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Events!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Listen for clicks on the button.
btn.
('click', () => alert('hi'));
The canonical way to attach a handler.
Discussion
Loading…