Event Types in JavaScript
Events in JavaScript are actions or occurrences that can be detected and handled in an application. They are the core of JavaScript’s event-driven model and can be triggered by user interactions, browser activities, or system processes.
1. User Interface (UI) Events
UI events are triggered by actions related to the browser window, page, or element rendering. They allow your application to respond when the page loads, the window is resized, or something goes wrong.
load
: Fires when the entire page, including all resources like images and scripts, has completely loaded.
window.addEventListener("load", () => {
console.log("Page fully loaded");
});
resize
: Fires whenever the browser window is resized. Useful for responsive layouts.
window.addEventListener("resize", () => {
console.log("Window resized");
});
scroll
: Fires when the user scrolls the page or a specific element. Often used for scroll animations or infinite scrolling.
window.addEventListener("scroll", () => {
console.log("User is scrolling");
});
error
: Fires when a resource, like an image or script, fails to load. Allows you to handle broken resources.
const img = document.querySelector("img");
img.addEventListener("error", () => {
console.log("Image failed to load");
});
2. Mouse Events
Mouse events are triggered by user interactions with the mouse, like clicks, movements, or button presses. They allow your application to respond to mouse activity on elements or the document.
click
: Fires when the user clicks an element.
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked");
});
dblclick
: Fires when the user double-clicks an element.
button.addEventListener("dblclick", () => {
console.log("Button double-clicked");
});
mouseover
: Fires when the mouse pointer enters an element. Often used for hover effects.
const box = document.getElementById("box");
box.addEventListener("mouseover", () => {
console.log("Mouse over the box");
});
mouseout
: Fires when the mouse pointer leaves an element.
box.addEventListener("mouseout", () => {
console.log("Mouse left the box");
});
mousemove
: Fires whenever the mouse moves inside an element. Useful for drawing apps or games.
document.addEventListener("mousemove", e => {
console.log(`Mouse position: ${e.clientX}, ${e.clientY}`);
});
mousedown
/ mouseup
: Fires when a mouse button is pressed or released.
box.addEventListener("mousedown", () => console.log("Mouse down"));
box.addEventListener("mouseup", () => console.log("Mouse up"));
3. Keyboard Events
Keyboard events are triggered by user interactions with the keyboard. They allow your application to respond when the user presses or releases keys.
keydown
: Fires when a key is pressed down. This event occurs before the character is actually added to an input field.
document.addEventListener("keydown", event => {
console.log("Key pressed down:", event.key);
});
keyup
: Fires when a key is released. Useful for detecting when typing stops.
document.addEventListener("keyup", event => {
console.log("Key released:", event.key);
});
keypress
(deprecated): Fires when a key that produces a character is pressed. Modern browsers recommend using keydown
or input
events instead.
document.addEventListener("keypress", event => {
console.log("Key pressed:", event.key);
4. Form Events
Form events are triggered by user interactions with form elements such as inputs, checkboxes, radio buttons, and forms themselves. They allow you to handle data input, submission, and validation dynamically.
Common Form Events:
submit
: Fires when a form is submitted. Often used to validate data before sending it to the server.
const form = document.getElementById("myForm");
form.addEventListener("submit", event => {
event.preventDefault(); // Prevent default submission
console.log("Form submitted");
});
change
: Fires when an input's value changes and loses focus. Useful for dropdowns, checkboxes, or radio buttons.
const input = document.getElementById("myInput");
input.addEventListener("change", () => {
console.log("Input value changed:", input.value);
});
input
: Fires immediately as the value of an input changes. Great for real-time validation or search suggestions.
input.addEventListener("input", () => {
console.log("Typing:", input.value);
});
focus
/ blur
: Fires when an element gains (focus
) or loses (blur
) focus.
input.addEventListener("focus", () => console.log("Input focused"));
input.addEventListener("blur", () => console.log("Input lost focus"));
5. Clipboard Events
Clipboard events are triggered when the user performs copy, cut, or paste actions. These events allow you to interact with the clipboard, modify content, or prevent default actions.
Common Clipboard Events:
copy
: Fires when content is copied to the clipboard. You can modify the copied content using the event.clipboardData
object.
document.addEventListener("copy", event => {
console.log("Content copied!");
// Optionally modify clipboard content
// event.clipboardData.setData("text/plain", "Custom content");
// event.preventDefault(); // Required to override default
});
cut
: Fires when content is cut (removed and copied to clipboard).
document.addEventListener("cut", () => {
console.log("Content cut!");
});
paste
: Fires when content is pasted from the clipboard. You can access the pasted data using event.clipboardData
.
document.addEventListener("paste", event => {
const pastedData = event.clipboardData.getData("text");
console.log("Pasted content:", pastedData);
});
6. Drag & Drop Events
Drag & Drop events allow users to drag elements and drop them elsewhere on a web page. JavaScript can detect and respond to these actions, enabling interactive interfaces like file uploads or rearranging items.
Common Drag & Drop Events:
dragstart
: Fires when the user starts dragging an element.
const draggable = document.getElementById("dragItem");
draggable.addEventListener("dragstart", () => {
console.log("Drag started");
});
dragover
: Fires when a dragged element is over a drop target.
const dropZone = document.getElementById("dropZone");
dropZone.addEventListener("dragover", e => {
e.preventDefault(); // Necessary to allow drop
console.log("Dragging over drop zone");
});
drop
: Fires when the dragged element is dropped on a valid target.
dropZone.addEventListener("drop", e => {
e.preventDefault();
console.log("Dropped!");
});
7. Touch Events (Mobile / Tablet)
Touch events are triggered when a user interacts with a touch-enabled device like smartphones or tablets. These events help handle gestures like tapping, swiping, or pinching.
Common Touch Events:
touchstart
: Fires when the user touches the screen.
document.addEventListener("touchstart", () => {
console.log("Finger touched the screen");
});
touchmove
: Fires when the user moves their finger across the screen.
document.addEventListener("touchmove", e => {
console.log(`Finger moved to x:${e.touches[0].clientX}, y:${e.touches[0].clientY}`);
});
touchend
: Fires when the user lifts their finger from the screen.
document.addEventListener("touchend", () => {
console.log("Finger lifted from the screen");
});
8. Custom Events
Custom events allow developers to create and trigger their own events in JavaScript, enabling communication between different parts of an application beyond standard browser events. They are useful for modular and event-driven programming.
Creating a Custom Event:
const myEvent = new CustomEvent("myEvent", {
detail: { message: "Hello World" } // Optional data to pass
});
The detail
property allows sending custom data with the event.
Listening for a Custom Event:
document.addEventListener("myEvent", (e) => {
console.log(e.detail.message); // Access data from the event
});
Dispatching a Custom Event:
document.dispatchEvent(myEvent); // Triggers the "myEvent"