Lesson 07-Javascript Events

EventTarget Interface

The EventTarget interface primarily provides three instance methods:

  • addEventListener: Binds an event listener function.
  • removeEventListener: Removes an event listener function.
  • dispatchEvent: Triggers an event.

Event Model

The browser’s event model responds to events through listener functions. When an event occurs, the browser detects it and executes the corresponding listener. This is the primary programming approach in event-driven programming.

Binding Event Listeners

JavaScript provides three methods to bind event listeners:

<!-- Method 1: Directly define listener code for certain events -->
<body onload="doSomething()"></body>
<div onclick="console.log('Event triggered')"></div>

<!-- Method 2: Event properties on element nodes -->
<script>
window.onload = doSomething;
div.onclick = function (event) {
  console.log('Event triggered');
};
</script>

<!-- Method 3: addEventListener -->
<script>
window.addEventListener('load', doSomething, false);
</script>

Event Propagation

Events propagate in three phases:

  1. Capture Phase: From the window object to the target node (top-down).
  2. Target Phase: Triggered on the target node.
  3. Bubbling Phase: From the target node back to the window object (bottom-up).

Event Delegation

Since events bubble up to parent nodes, listener functions for child nodes can be defined on a parent node to handle events from multiple child elements. This is called event delegation.

var ul = document.querySelector('ul');
ul.addEventListener('click', function (event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    // some code
  }
});

// Stop propagation to prevent further downward spread at the p element
p.addEventListener('click', function (event) {
  event.stopPropagation();
}, true);

// Stop bubbling to prevent upward spread at the p element
p.addEventListener('click', function (event) {
  event.stopPropagation();
}, false);

Event Object

Instance Properties

  • Event.bubbles
  • Event.eventPhase
  • Event.cancelable
  • Event.cancelBubble
  • Event.defaultPrevented
  • Event.currentTarget
  • Event.target
  • Event.type
  • Event.timeStamp
  • Event.isTrusted
  • Event.detail

Instance Methods

  • Event.preventDefault()
  • Event.stopPropagation()
  • Event.stopImmediatePropagation()
  • Event.composedPath()

Mouse Events

Types of Mouse Events

  • click: Triggered when the mouse is clicked (typically the primary button).
  • dblclick: Triggered on double-clicking an element.
  • mousedown: Triggered when a mouse button is pressed.
  • mouseup: Triggered when a pressed mouse button is released.
  • mousemove: Triggered when the mouse moves within a node. Continuous movement triggers this repeatedly; to avoid performance issues, limit its execution (e.g., throttle to run once within a time frame).
  • mouseenter: Triggered when the mouse enters a node, not triggered on entering child nodes.
  • mouseover: Triggered when the mouse enters a node, triggered again on entering child nodes.
  • mouseout: Triggered when the mouse leaves a node, also triggered when leaving a parent node.
  • mouseleave: Triggered when the mouse leaves a node, not triggered when leaving a parent node.
  • contextmenu: Triggered when the right mouse button or context menu key is pressed (before the context menu appears).
  • wheel: Triggered when the mouse wheel is scrolled, inheriting the WheelEvent interface.

MouseEvent Interface Overview

The MouseEvent interface represents mouse-related events. Events like click, dblclick, mouseup, mousedown, as well as wheel and drag events, generate MouseEvent instances.

// The MouseEvent constructor takes two parameters: event type (string) and an optional configuration object.
var event = new MouseEvent(type, options);

Configuration object properties (all optional):

  • screenX: Number, mouse’s horizontal position relative to the screen (pixels), default 0. Setting does not move the mouse.
  • screenY: Number, mouse’s vertical position relative to the screen (pixels), default 0.
  • clientX: Number, mouse’s horizontal position relative to the browser window (pixels), default 0.
  • clientY: Number, mouse’s vertical position relative to the browser window (pixels), default 0.
  • ctrlKey: Boolean, whether the Ctrl key is pressed, default false.
  • shiftKey: Boolean, whether the Shift key is pressed, default false.
  • altKey: Boolean, whether the Alt key is pressed, default false.
  • metaKey: Boolean, whether the Meta key is pressed, default false.
  • button: Number, which mouse button was pressed: 0 (primary, typically left), 1 (auxiliary, typically middle), 2 (secondary, typically right), default 0.
  • buttons: Number, a three-bit binary indicating pressed buttons: 0 (none), 1 (primary), 2 (secondary), 4 (auxiliary). E.g., 3 means primary and secondary pressed.
  • relatedTarget: Node object, the related node, default null. For mouseenter/mouseover, the node just left; for mouseout/mouseleave, the node being entered.

MouseEvent Instance Properties

  • MouseEvent.altKey, MouseEvent.ctrlKey, MouseEvent.metaKey, MouseEvent.shiftKey: Booleans indicating whether the respective keys were pressed (read-only).
  • MouseEvent.button: Number indicating which button was pressed (read-only):
  • 0: Primary button (left) or uninitialized (e.g., mousemove).
  • 1: Auxiliary button (middle).
  • 2: Secondary button (right).
  • MouseEvent.buttons: Number indicating pressed buttons (read-only).
  • MouseEvent.clientX, MouseEvent.clientY: Mouse coordinates relative to the browser window’s top-left corner (pixels, read-only).
  • MouseEvent.movementX: Horizontal distance from the last mousemove event (pixels).
  • MouseEvent.screenX, MouseEvent.screenY: Mouse coordinates relative to the screen’s top-left corner (pixels, read-only).
  • MouseEvent.offsetX, MouseEvent.offsetY: Mouse distance from the target node’s padding edge (pixels, read-only).
  • MouseEvent.pageX, MouseEvent.pageY: Mouse distance from the document’s left/top edge, including scrolled areas (pixels, read-only).

MouseEvent Instance Methods

  • MouseEvent.getModifierState(): Returns a boolean indicating if a specific modifier key is pressed. Takes a string parameter (e.g., 'CapsLock').
document.addEventListener('click', function (e) {
  console.log(e.getModifierState('CapsLock'));
}, false);

WheelEvent Interface

The WheelEvent interface, inheriting from MouseEvent, represents mouse wheel events. The wheel event is the only wheel-related event.

Keyboard Events

Keyboard events are triggered by key presses, including keydown, keypress, and keyup, all inheriting the KeyboardEvent interface.

  • keydown: Triggered when a key is pressed.
  • keypress: Triggered when a value-producing key is pressed (not triggered by Ctrl, Alt, Shift, or Meta). Follows keydown for value keys.
  • keyup: Triggered when a key is released.

Progress Events

Progress events track resource loading, primarily triggered by AJAX requests, <img>, <audio>, <video>, <style>, <link>, etc., inheriting the ProgressEvent interface. They include:

  • abort: Triggered when loading is aborted (e.g., by the user), not triggered on errors.
  • error: Triggered when loading fails due to an error.
  • load: Triggered on successful loading.
  • loadstart: Triggered when loading begins.
  • loadend: Triggered when loading stops, after error, abort, or load.
  • progress: Triggered continuously during loading.
  • timeout: Triggered on timeout.

Form Events

Types of Form Events

  • input
  • select
  • change
  • invalid
  • reset
  • submit

Touch Events

The browser’s touch API consists of three components:

  • Touch: A single touch point.
  • TouchList: A collection of touch points.
  • TouchEvent: Events triggered by touch.

Touch Interface

var touch = new Touch(touchOptions);

Configuration object properties:

  • identifier: Required, integer, unique ID for the touch point.
  • target: Required, element node where the touch began.
  • clientX: Optional, number, horizontal distance from the browser window’s top-left (pixels), default 0.
  • clientY: Optional, number, vertical distance from the browser window’s top-left (pixels), default 0.
  • screenX: Optional, number, horizontal distance from the screen’s top-left (pixels), default 0.
  • screenY: Optional, number, vertical distance from the screen’s top-left (pixels), default 0.
  • pageX: Optional, number, horizontal distance from the webpage’s top-left, including scroll (pixels), default 0.
  • pageY: Optional, number, vertical distance from the webpage’s top-left, including scroll (pixels), default 0.
  • radiusX: Optional, number, X-axis radius of the affected elliptical area (pixels), default 0.
  • radiusY: Optional, number, Y-axis radius of the affected elliptical area (pixels), default 0.
  • rotationAngle: Optional, number, rotation angle of the touch ellipse (degrees, 0–90), default 0.
  • force: Optional, number (0–1), touch pressure (0 = none, 1 = max hardware pressure), default 0.

TouchList Interface

Properties and Methods:

  • TouchList.length: Number of touch points.
  • TouchList.item(): Returns the touch point at the specified index (zero-based).

TouchEvent Interface

Properties:

  • TouchEvent.altKey, TouchEvent.ctrlKey, TouchEvent.shiftKey, TouchEvent.metaKey
  • TouchEvent.changedTouches
  • TouchEvent.touches
  • TouchEvent.targetTouches

Types of Touch Events

  • touchstart: Triggered when a touch begins, target is the touched element.
  • touchend: Triggered when a touch ends (e.g., finger lifts or moves off-screen), target matches touchstart. changedTouches contains ended touch points.
  • touchmove: Triggered when a touch point moves, target matches touchstart. Also triggered if radius, angle, or force changes.
  • touchcancel: Triggered when a touch is canceled (e.g., modal window appears, touch leaves document, or too many touch points).

Drag-and-Drop Events

Types of Drag-and-Drop Events

  • drag: Triggered continuously on the dragged node during dragging (every few hundred milliseconds).
  • dragstart: Triggered on the dragged node when dragging begins, target is the dragged node. Specify drag data in its listener.
  • dragend: Triggered on the dragged node when dragging ends (mouse release or ESC key), target is the dragged node. Always triggered, regardless of window crossing or cancellation.
  • dragenter: Triggered once when dragging enters a node, target is the current node. Specify whether dropping is allowed in its listener.
  • dragover: Triggered continuously when dragging over a node (every few hundred milliseconds), target is the current node. Unlike dragenter, it keeps triggering while over the node.
  • dragleave: Triggered when dragging leaves a node, target is the current node. Use its listener for visual feedback.
  • drop: Triggered when the dragged node or text is dropped on a target node, only if the target allows dropping. Not triggered if ESC is pressed or dropping is disallowed.

DataTransfer Instance Properties

  • DataTransfer.dropEffect
  • DataTransfer.effectAllowed
  • DataTransfer.files
  • DataTransfer.types
  • DataTransfer.items

DataTransfer Instance Methods

  • DataTransfer.setData()
  • DataTransfer.getData()
  • DataTransfer.clearData()
  • DataTransfer.setDragImage()

Other Common Events

Resource Events

  • beforeunload: Triggered before a window, document, or resource is unloaded, useful for preventing accidental unloading.
  • unload: Triggered when a window closes or document is unloaded, after beforeunload and pagehide.
  • load: Triggered when a page or resource loads successfully.
  • error: Triggered when a page or resource fails to load. abort is triggered on user cancellation.
  • pageshow: Triggered when a page loads, including initial and cached loads. Use its listener for code that runs every load.
  • pagehide: Triggered when leaving a page via navigation buttons, unlike unload, pages are cached.
  • popstate: Triggered when the history object’s current record changes explicitly, not by pushState() or replaceState().
  • hashchange: Triggered when the URL’s hash changes, typically listened to on the window object.

Document State Events

  • DOMContentLoaded: Triggered on the document object when the webpage is downloaded and parsed.
  • readystatechange: Triggered when the readyState of Document or XMLHttpRequest changes.

Window Events

  • scroll: Triggered when the document or an element scrolls, typically during scrollbar interaction.
  • resize: Triggered when the browser window is resized, occurring on the window object.
  • fullscreenchange: Triggered on the document object when entering or exiting fullscreen mode.
  • fullscreenerror: Triggered when the browser fails to enter fullscreen mode.
  • Clipboard Events: Related to clipboard operations.
  • Focus Events: Related to gaining or losing focus on elements or the document.

GlobalEventHandlers Interface

  • GlobalEventHandlers.onabort
  • GlobalEventHandlers.onerror
  • GlobalEventHandlers.onload, GlobalEventHandlers.onloadstart
  • GlobalEventHandlers.onfocus, GlobalEventHandlers.onblur
  • GlobalEventHandlers.onscroll
  • GlobalEventHandlers.oncontextmenu, GlobalEventHandlers.onshow
Share your love