iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ApproachExampleWhen to use
Inline attribute<button onclick="…">Quick demos only. Mixes structure + behaviour.
Property assignmentel.onclick = fnSimple — but you can only attach one handler.
addEventListenerel.addEventListener("click", fn)The right answer for real apps. Multiple listeners, options.

The most-used events

EventFires when…
clickMouse click or touch tap.
inputForm field value changes — every keystroke.
changeField commits a change (e.g. blur on text, selection on select).
submitForm is submitted. Use e.preventDefault() to handle in JS.
keydown / keyupKey pressed / released.
scrollElement scrolled. Throttle for performance.
load / DOMContentLoadedPage assets fully loaded / DOM is parsed.
mouseenter / mouseleavePointer 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'));

Test yourself

Q1. Attach multiple click handlers to one element with…
Q2. Prevent a form from submitting natively with…
Q3. Event delegation listens on…

Discussion

Loading…