HTML5 - Events
HTML5 - Events
Section titled “HTML5 - Events”Events are actions or occurrences that happen in the browser, often triggered by user interactions (like clicking a button, moving the mouse, pressing a key) or by the browser itself (like a page finishing loading, a video starting to play, or an error occurring).
JavaScript allows you to detect these events and execute code in response, making web pages interactive and dynamic. This code is often referred to as an ‘event handler’ or ‘event listener’.
HTML5 supports a wide range of events applicable to various elements and browser states.
Assigning Event Handlers
Section titled “Assigning Event Handlers”There are several ways to assign event handlers:
- Inline Event Handler Attributes (Less Recommended): Directly adding attributes like
onclick,onmouseoverto HTML elements. This mixes HTML and JavaScript logic and is generally discouraged for larger applications. - DOM Element Properties: Assigning a function to the element’s corresponding
on<eventtype>property in JavaScript (e.g.,buttonElement.onclick = myFunction;). Only one handler can be assigned per event type this way. addEventListener()(Recommended): The modern and most flexible approach. Allows attaching multiple independent listeners for the same event type to an element, and provides more control over the event capturing/bubbling phase.
Example using addEventListener()
Section titled “Example using addEventListener()”<!DOCTYPE html><html><head> <title>Event Listener Example</title></head><body> <button id="myButton">Click Me</button> <p id="output"></p>
<script> const button = document.getElementById('myButton'); const output = document.getElementById('output');
function handleClick(event) { // 'event' object contains information about the event console.log('Button clicked!', event); output.textContent = `Button clicked at ${new Date().toLocaleTimeString()}`; }
function handleMouseOver() { console.log('Mouse is over the button'); button.style.backgroundColor = 'lightblue'; }
function handleMouseOut() { console.log('Mouse left the button'); button.style.backgroundColor = ''; // Reset style }
// Attach event listeners button.addEventListener('click', handleClick); button.addEventListener('mouseover', handleMouseOver); button.addEventListener('mouseout', handleMouseOut);
// To remove a listener later: // button.removeEventListener('click', handleClick); </script></body></html>Common Event Categories and Examples
Section titled “Common Event Categories and Examples”HTML5 events can be broadly categorized:
Mouse Events
Section titled “Mouse Events”click: Fired when the primary mouse button is clicked on an element.dblclick: Fired when the primary mouse button is double-clicked.mousedown: Fired when a mouse button is pressed down over an element.mouseup: Fired when a mouse button is released over an element.mousemove: Fired when the mouse pointer moves while over an element.mouseover: Fired when the mouse pointer enters an element or its children.mouseout: Fired when the mouse pointer leaves an element or its children.mouseenter: Similar tomouseover, but doesn’t bubble and doesn’t fire when moving between descendants.mouseleave: Similar tomouseout, but doesn’t bubble.contextmenu: Fired when the right mouse button is clicked (or context menu is otherwise triggered).
Keyboard Events
Section titled “Keyboard Events”keydown: Fired when a key is pressed down.keyup: Fired when a key is released.keypress: Fired when a key that produces a character value is pressed down (usekeydownfor more general key detection).
Form Events
Section titled “Form Events”submit: Fired on the<form>element when it is submitted.reset: Fired on the<form>element when it is reset.change: Fired for<input>,<select>, and<textarea>elements when their value changes and they lose focus.input: Fired for<input>,<select>, and<textarea>elements immediately when their value changes.focus: Fired when an element receives focus.blur: Fired when an element loses focus.invalid: Fired on a form control when it fails constraint validation.
Document/Window Events
Section titled “Document/Window Events”load: Fired onwindowwhen the whole page (including resources like images and stylesheets) has finished loading.DOMContentLoaded: Fired ondocumentwhen the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Often preferred overloadfor initializing scripts that interact with the DOM.unload: Fired onwindowwhen the page is being unloaded.beforeunload: Fired onwindowjust before the page unloads. Can be used to prompt the user if they want to leave the page.resize: Fired onwindowwhen the browser window is resized.scroll: Fired onwindowor any scrollable element when it is scrolled.
Media Events (for <audio>, <video>)
Section titled “Media Events (for <audio>, <video>)”play: Fired when playback begins or resumes.pause: Fired when playback is paused.ended: Fired when playback reaches the end of the media.timeupdate: Fired frequently as the current playback position changes.volumechange: Fired when the volume or muted state changes.canplay: Fired when the browser can start playing, but might need to buffer.canplaythrough: Fired when the browser estimates it can play through to the end without buffering.error: Fired if an error occurs while fetching or playing media.loadeddata: Fired when the first frame of the media has loaded.progress: Fired periodically as the browser downloads the media data.
Drag & Drop Events
Section titled “Drag & Drop Events”dragstart: Fired on the draggable element when dragging starts.drag: Fired repeatedly on the draggable element as it’s dragged.dragend: Fired on the draggable element when dragging ends.dragenter: Fired on a potential drop target when a dragged item enters it.dragover: Fired repeatedly on a potential drop target as a dragged item is over it (must callevent.preventDefault()here to allow dropping).dragleave: Fired on a potential drop target when a dragged item leaves it.drop: Fired on the drop target when the item is dropped onto it.
Other Events
Section titled “Other Events”online: Fired when the browser gains network connectivity.offline: Fired when the browser loses network connectivity.popstate: Fired onwindowwhen the active history entry changes (e.g., back/forward button).storage: Fired onwindowwhen a Web Storage area (localStorageorsessionStorage) is modified in another document from the same origin.- Transition/Animation Events (
transitionend,animationend). - Pointer Events (modern alternative to mouse/touch events:
pointerdown,pointermove,pointerup, etc.).
This is not an exhaustive list. Many APIs (like WebSockets, Server-Sent Events, Web Workers, IndexedDB) have their own specific events. Refer to MDN Web Docs for a comprehensive list and details on each event: (https://developer.mozilla.org/en-US/docs/Web/Events)