TutorialsJSJS Events
Share:

JS Events

advanced

Part of JavaScript in the Browser

Theory

Events are actions or occurrences that happen in the browser — clicks, key presses, mouse movements, form submissions, page loads — that JavaScript can detect and respond to.

addEventListener is the modern way to attach event handlers. The syntax is element.addEventListener(eventType, handlerFunction, useCapture). You can attach multiple listeners to the same element for the same event type. For removal, use removeEventListener with the same handler reference.

Common event types:

  • Mouse: click, dblclick, mouseover, mouseout, mousedown, mouseup, mousemove
  • Keyboard: keydown, keyup, keypress (deprecated, prefer keydown)
  • Form: submit, input, change, focus, blur
  • Document/Window: DOMContentLoaded, load, resize, scroll, beforeunload

The Event Object is automatically passed to handler functions. Key properties: target (the element that triggered the event), currentTarget (the element the listener is on), type, clientX/clientY (mouse coordinates), key (keyboard key), preventDefault() (cancels default behavior), and stopPropagation() (stops event bubbling).

Event propagation happens in three phases: capturing (root to target), target (at the element), and bubbling (target back to root). By default, listeners run in the bubbling phase. Setting the third argument of addEventListener to true runs the listener in the capturing phase.

Event delegation is a pattern where you attach a single listener to a parent element instead of many listeners to child elements. Use e.target to identify which child triggered the event. This improves performance for dynamic lists and large numbers of elements.

preventDefault() stops the browser's default action (like following a link or submitting a form). stopPropagation() stops the event from traveling further up or down the DOM tree.

Event Handling Examples
javascript
Event Delegation and Propagation
javascript

Exercises

Click Counter with Event Delegation

easy

Create a page with a ul element (id click-list) containing five li items labeled Item 1 through Item 5. Write JS using event delegation to log Clicked: Item X when any li is clicked and track the total click count.

Starter Code:

let clickCount = 0;\nconst list = document.getElementById('click-list');\n// Use event delegation here

Expected Output:

Clicked: Item 1 (click count: 1)\nClicked: Item 3 (click count: 2)

Mini Quiz

Mini Quiz