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:
- Capture Phase: From the
windowobject to the target node (top-down). - Target Phase: Triggered on the target node.
- Bubbling Phase: From the target node back to the
windowobject (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.bubblesEvent.eventPhaseEvent.cancelableEvent.cancelBubbleEvent.defaultPreventedEvent.currentTargetEvent.targetEvent.typeEvent.timeStampEvent.isTrustedEvent.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 theWheelEventinterface.
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), default0. Setting does not move the mouse.screenY: Number, mouse’s vertical position relative to the screen (pixels), default0.clientX: Number, mouse’s horizontal position relative to the browser window (pixels), default0.clientY: Number, mouse’s vertical position relative to the browser window (pixels), default0.ctrlKey: Boolean, whether the Ctrl key is pressed, defaultfalse.shiftKey: Boolean, whether the Shift key is pressed, defaultfalse.altKey: Boolean, whether the Alt key is pressed, defaultfalse.metaKey: Boolean, whether the Meta key is pressed, defaultfalse.button: Number, which mouse button was pressed:0(primary, typically left),1(auxiliary, typically middle),2(secondary, typically right), default0.buttons: Number, a three-bit binary indicating pressed buttons:0(none),1(primary),2(secondary),4(auxiliary). E.g.,3means primary and secondary pressed.relatedTarget: Node object, the related node, defaultnull. Formouseenter/mouseover, the node just left; formouseout/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 lastmousemoveevent (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). Followskeydownfor 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, aftererror,abort, orload.progress: Triggered continuously during loading.timeout: Triggered on timeout.
Form Events
Types of Form Events
inputselectchangeinvalidresetsubmit
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), default0.clientY: Optional, number, vertical distance from the browser window’s top-left (pixels), default0.screenX: Optional, number, horizontal distance from the screen’s top-left (pixels), default0.screenY: Optional, number, vertical distance from the screen’s top-left (pixels), default0.pageX: Optional, number, horizontal distance from the webpage’s top-left, including scroll (pixels), default0.pageY: Optional, number, vertical distance from the webpage’s top-left, including scroll (pixels), default0.radiusX: Optional, number, X-axis radius of the affected elliptical area (pixels), default0.radiusY: Optional, number, Y-axis radius of the affected elliptical area (pixels), default0.rotationAngle: Optional, number, rotation angle of the touch ellipse (degrees, 0–90), default0.force: Optional, number (0–1), touch pressure (0 = none, 1 = max hardware pressure), default0.
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.metaKeyTouchEvent.changedTouchesTouchEvent.touchesTouchEvent.targetTouches
Types of Touch Events
touchstart: Triggered when a touch begins,targetis the touched element.touchend: Triggered when a touch ends (e.g., finger lifts or moves off-screen),targetmatchestouchstart.changedTouchescontains ended touch points.touchmove: Triggered when a touch point moves,targetmatchestouchstart. 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,targetis the dragged node. Specify drag data in its listener.dragend: Triggered on the dragged node when dragging ends (mouse release or ESC key),targetis the dragged node. Always triggered, regardless of window crossing or cancellation.dragenter: Triggered once when dragging enters a node,targetis the current node. Specify whether dropping is allowed in its listener.dragover: Triggered continuously when dragging over a node (every few hundred milliseconds),targetis the current node. Unlikedragenter, it keeps triggering while over the node.dragleave: Triggered when dragging leaves a node,targetis 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.dropEffectDataTransfer.effectAllowedDataTransfer.filesDataTransfer.typesDataTransfer.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, afterbeforeunloadandpagehide.load: Triggered when a page or resource loads successfully.error: Triggered when a page or resource fails to load.abortis 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, unlikeunload, pages are cached.popstate: Triggered when thehistoryobject’s current record changes explicitly, not bypushState()orreplaceState().hashchange: Triggered when the URL’s hash changes, typically listened to on thewindowobject.
Document State Events
DOMContentLoaded: Triggered on thedocumentobject when the webpage is downloaded and parsed.readystatechange: Triggered when thereadyStateofDocumentorXMLHttpRequestchanges.
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 thewindowobject.fullscreenchange: Triggered on thedocumentobject 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.onabortGlobalEventHandlers.onerrorGlobalEventHandlers.onload,GlobalEventHandlers.onloadstartGlobalEventHandlers.onfocus,GlobalEventHandlers.onblurGlobalEventHandlers.onscrollGlobalEventHandlers.oncontextmenu,GlobalEventHandlers.onshow



