Skip to content

Events

An event is an action triggered by the user or the browser:
mouse click, key press, page load, etc.

JavaScript lets you respond to these events by running code.


The modern method is addEventListener().
It allows listening for an event and defining the function to execute.

let button = document.getElementById("myButton");
button.addEventListener("click", () => {
alert("Button clicked!");
});

Advantage: you can attach multiple listeners to the same element and remove them with removeEventListener.


  • click → mouse click
  • mouseover → mouse hover
  • keydown → keyboard key pressed
  • submit → form submission

When an event fires, the callback function automatically receives an event object.
This object contains all the information about the action that occurred.

Useful properties:

  • event.type → event type (click, keydown, etc.)
  • event.target → element that triggered the event
  • event.key → key pressed (keyboard events only)
  • event.clientX / event.clientY → click coordinates (mouse events)
document.addEventListener("keydown", (event) => {
console.log("Type:", event.type); // "keydown"
console.log("Key pressed:", event.key); // e.g. "a"
});

document.addEventListener("click", (event) => {
console.log("Element clicked:", event.target);
console.log("Click position:", event.clientX, event.clientY);
});

The event object is essential for making your code more responsive and precise.


<input type="text" id="inputField" placeholder="Type something">
<p id="display"></p>
<script>
let inputField = document.getElementById("inputField");
let display = document.getElementById("display");
inputField.addEventListener("input", () => {
display.innerText = inputField.value;
});
</script>

Here, the paragraph updates in real-time as you type.


By default, events go through two phases:

  1. Capturing → the event travels from the document down to the target element in the DOM tree.
  2. Bubbling → after triggering, the event bubbles up from the target element to its ancestors.

This mechanism enables event delegation: handling events at a parent level instead of attaching listeners to each child individually.
Very useful for lists or dynamically added elements.


  • Use addEventListener instead of onclick="..." in HTML (cleaner and more flexible).
  • Always utilize the event object for useful information (event.target, event.key, etc.).
  • Remove unnecessary listeners with removeEventListener to avoid memory leaks.
  • Prefer event delegation (listen on a parent instead of each child) for better performance.