Skip to content

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.

There are several ways to assign event handlers:

  1. Inline Event Handler Attributes (Less Recommended): Directly adding attributes like onclick, onmouseover to HTML elements. This mixes HTML and JavaScript logic and is generally discouraged for larger applications.
  2. 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.
  3. 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.
<!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>

HTML5 events can be broadly categorized:

  • 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 to mouseover, but doesn’t bubble and doesn’t fire when moving between descendants.
  • mouseleave: Similar to mouseout, but doesn’t bubble.
  • contextmenu: Fired when the right mouse button is clicked (or context menu is otherwise triggered).
  • 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 (use keydown for more general key detection).
  • 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.
  • load: Fired on window when the whole page (including resources like images and stylesheets) has finished loading.
  • DOMContentLoaded: Fired on document when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Often preferred over load for initializing scripts that interact with the DOM.
  • unload: Fired on window when the page is being unloaded.
  • beforeunload: Fired on window just before the page unloads. Can be used to prompt the user if they want to leave the page.
  • resize: Fired on window when the browser window is resized.
  • scroll: Fired on window or any scrollable element when it is scrolled.
  • 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.
  • 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 call event.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.
  • online: Fired when the browser gains network connectivity.
  • offline: Fired when the browser loses network connectivity.
  • popstate: Fired on window when the active history entry changes (e.g., back/forward button).
  • storage: Fired on window when a Web Storage area (localStorage or sessionStorage) 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)