Events
What is an event?
Section titled “What is an event?”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.
Adding an event listener
Section titled “Adding an event listener”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
.
Common event types
Section titled “Common event types”click
→ mouse clickmouseover
→ mouse hoverkeydown
→ keyboard key pressedsubmit
→ form submission
Using the event
object
Section titled “Using the event object”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 eventevent.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"});
Click example
Section titled “Click example”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.
Practical example
Section titled “Practical example”<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.
Event propagation
Section titled “Event propagation”By default, events go through two phases:
- Capturing → the event travels from the document down to the target element in the DOM tree.
- 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.
Best practices
Section titled “Best practices”- Use
addEventListener
instead ofonclick="..."
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.