JavaScript Events

🎯 Introduction to Events

Events are actions or occurrences that happen in the browser, such as clicks, key presses, or page loads. JavaScript can detect these events and execute code in response.

JavaScript Editor
Common Event Types:
  • Mouse Events: click, dblclick, mousedown, mouseup
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, change, focus, blur
  • Window Events: load, resize, scroll
Event Handler Methods:
  • addEventListener() - Recommended method
  • onclick - Inline property (limited)
  • element.onclick = function() - DOM property

📋 The Event Object

When an event occurs, the browser creates an event object containing information about the event. This object is passed to the event handler function.

JavaScript Editor
Common Properties:
  • type - Event type (click, keydown, etc.)
  • target - Element that triggered event
  • currentTarget - Element with listener
  • clientX/clientY - Mouse coordinates
Keyboard Properties:
  • key - Character value
  • code - Physical key code
  • ctrlKey/shiftKey/altKey - Modifier keys
Event Methods:
  • preventDefault() - Prevent default action
  • stopPropagation() - Stop event flow
  • stopImmediatePropagation() - Stop all handlers

🌊 Event Flow: Bubbling & Capturing

Events in the DOM have three phases: capturing, target, and bubbling. Understanding this flow is crucial for complex event handling.

JavaScript Editor
Event Flow Phases:
  1. Capturing Phase: Window → Document → ... → Parent
  2. Target Phase: Event reaches target element
  3. Bubbling Phase: Target → Parent → ... → Window
Flow Control Methods:
  • stopPropagation() - Stops event flow
  • stopImmediatePropagation() - Stops all handlers
  • preventDefault() - Prevents default action

🎪 Event Delegation Pattern

Event delegation is a technique where you attach a single event listener to a parent element instead of multiple listeners to child elements. This is more efficient and works with dynamically added elements.

JavaScript Editor
✅ Event Delegation Benefits:
  • Performance: Single listener instead of many
  • Memory: Less memory usage
  • Dynamic Content: Works with elements added later
  • Cleaner Code: Centralized event handling

📋 Event Reference

Mouse Events:
  • click - Single click
  • dblclick - Double click
  • mousedown - Button pressed
  • mouseup - Button released
  • mousemove - Mouse moved
  • mouseenter - Enter element
  • mouseleave - Leave element
Keyboard Events:
  • keydown - Key pressed
  • keyup - Key released
  • keypress - Character input
Form Events:
  • submit - Form submitted
  • change - Input value changed
  • input - Input value changing
  • focus - Element focused
  • blur - Element lost focus
Window Events:
  • load - Page loaded
  • resize - Window resized
  • scroll - Page scrolled
  • beforeunload - Before page unload