JavaScript events can be broadly categorized into several types based on their origin or purpose. Here are examples of the different categories:
These events are triggered by direct user interaction with the webpage.
-
onclick
: Triggered when a user clicks on an element.document.getElementById("myButton").onclick = function() { alert("Button clicked!"); };
-
onkeydown
: Triggered when a user presses a key on the keyboard.document.addEventListener("keydown", function(event) { console.log(`Key pressed: ${event.key}`); });
-
onmouseover
: Triggered when a user hovers the mouse over an element.document.getElementById("myElement").onmouseover = function() { console.log("Mouse is over the element."); };
These events are generated by processes or states within the application, often without direct user interaction.
-
readystatechange
: Triggered when the readyState of a document changes.document.onreadystatechange = function() { if (document.readyState === "complete") { console.log("Document is fully loaded."); } };
-
websocket.onopen
: Triggered when a WebSocket connection is established.const ws = new WebSocket("ws://example.com/socket"); ws.onopen = function() { console.log("WebSocket connection opened."); };
-
onload
: Triggered when an object (like an image or script) has been loaded.window.onload = function() { console.log("Page fully loaded."); };
-
setInterval
andsetTimeout
: Though not events in the traditional sense, these functions can be used to trigger code execution after a certain period, often leading to a change or event in the application.setTimeout(function() { console.log("This message appears after 2 seconds."); }, 2000);
These are custom events that developers create and dispatch based on specific application logic.
-
Custom Event:
// Creating a custom event const myEvent = new CustomEvent("myCustomEvent", { detail: { message: "Hello, World!" } }); // Adding an event listener for the custom event document.addEventListener("myCustomEvent", function(event) { console.log("Custom event triggered:", event.detail.message); }); // Dispatching the custom event document.dispatchEvent(myEvent);
-
EventEmitter Pattern (often used in Node.js):
const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // Define a custom event myEmitter.on('event', () => { console.log('An event occurred!'); }); // Trigger the event myEmitter.emit('event');
These events are related to network activities like making an HTTP request or WebSocket communication.
-
onerror
: Triggered when an error occurs during resource loading.window.onerror = function(message, source, lineno, colno, error) { console.log("Error occurred:", message); };
-
fetch
: Triggered as part of a network request, though it returns a Promise rather than using an event listener.fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error fetching data:", error));
These are events that occur at specific points in the lifecycle of a webpage or component.
-
DOMContentLoaded
: Triggered when the initial HTML document has been completely loaded and parsed.document.addEventListener("DOMContentLoaded", function() { console.log("DOM fully loaded and parsed"); });
-
beforeunload
: Triggered when the user is about to leave the page.window.addEventListener("beforeunload", function(event) { event.preventDefault(); event.returnValue = ''; });
These examples cover various categories of events in JavaScript, demonstrating how they are triggered and handled in different scenarios.