Event listeners in JavaScript are like alert guards, standing by and waiting patiently for a specific action to happen on a particular element. This action could be anything – a mouse click on a button, a gentle hover over an element, the complete loading of a webpage, or even a simple stroke on your keyboard.
Once these actions take place, it’s showtime for the event listeners. They spring into action, triggering a block of code that you’ve assigned to them.
Let’s break it down with an example. Imagine we have this little chunk of JavaScript:
document.querySelector("button").addEventListener("click", function() {
alert("Button was clicked!");
});
In this scenario, we’re using the addEventListener
method to assign our alert guard (the event listener) to a button. We’ve told it to watch out for a “click” event. So, the moment someone clicks that button, our event listener swings into action, executing the function which pops up an alert saying “Button was clicked!”.
There are numerous event listeners available to handle user interactions or changes in the state of the elements. In this post, I’ll try to include a list of all the event listeners in JavaScript.
Animation Events
Animation events are used to detect when a CSS animation starts, ends, or completes an iteration.
animationstart
This event occurs when a CSS animation starts.
let animatedElement = document.querySelector('.animated-element');
animatedElement.addEventListener('animationstart', () => {
console.log('Animation started');
});
animationend
This event occurs when a CSS animation has completed.
let animatedElement = document.querySelector('.animated-element');
animatedElement.addEventListener('animationend', () => {
console.log('Animation ended');
});
animationiteration
This event is triggered every time a CSS animation finishes an iteration. If the animation is set to repeat infinitely (animation-iteration-count: infinite
), this event will be triggered at the end of each iteration.
let animatedElement = document.querySelector('.animated-element');
animatedElement.addEventListener('animationiteration', () => {
console.log('Animation iteration');
});
Remember that these events can only be used with CSS animations. If you’re animating elements with JavaScript, you’ll have to handle timing and completion in your JavaScript code.
Clipboard Events
JavaScript provides several clipboard events that can be used to interact with the user’s clipboard for copy, cut, and paste operations.
copy
This event is triggered when the user initiates a copy action (e.g., Ctrl+C).
document.addEventListener('copy', (event) => {
console.log('Copy event detected!');
});
cut
This event is fired when the user initiates a cut action (e.g., Ctrl+X).
document.addEventListener('cut', (event) => {
console.log('Cut event detected!');
});
paste
This event is triggered when the user initiates a paste action (e.g., Ctrl+V).
document.addEventListener('paste', (event) => {
console.log('Paste event detected!');
});
clipboardchange
This is a new event introduced with the Async Clipboard API. It fires whenever the clipboard contents are changed.
navigator.clipboard.addEventListener('clipboardchange', () => {
console.log('Clipboard contents changed!');
});
Please note that the clipboardchange
event is part of the Async Clipboard API, which is still experimental and not fully supported in all browsers.
Remember that due to browser security restrictions, clipboard events might not always provide access to the actual data that was copied, cut, or pasted.
Drag Events
JavaScript supports several drag and drop events, which are a part of the HTML5 specification. These events allow you to create draggable elements and define what happens when an element is dragged or dropped.
dragstart
This event is triggered when the user starts to drag an object.
document.addEventListener('dragstart', function(event) {
console.log('Strated Dragging!');
});
drag
The drag
event is fired every few hundred milliseconds as an element or text selection is being dragged by the user.
document.addEventListener('drag', function(event) {
console.log('Dragging!');
});
dragend
This event is triggered when a drag operation is being finished (by releasing a mouse button or hitting the escape key).
document.addEventListener('dragend', function(event) {
console.log('Drag ended!');
});
dragenter
The dragenter
event is fired when a dragged element or text selection enters a valid drop target.
document.addEventListener('dragenter', function(event) {
console.log('Entered valid drop target');
});
dragleave
This event is triggered when a dragged element leaves a drop target area.
document.addEventListener('dragleave', function(event) {
console.log('Left drop target area');
});
dragover
The dragover
event is fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).
document.addEventListener('dragover', function(event) {
event.preventDefault();
console.log('Currently dragging over a drop target area');
});
drop
This event is triggered when a dragged element is dropped on a valid drop target.
document.addEventListener('drop', function(event) {
event.preventDefault();
console.log('Element dropped');
});
Focus Events
Focus events handle the focus state of elements.
focus
This event is fired when an element has received focus.
let inputElement = document.querySelector('input');
inputElement.addEventListener('focus', function(event) {
console.log('Input received focus');
});
blur
This event is fired when an element has lost focus.
let inputElement = document.querySelector('input');
inputElement.addEventListener('blur', function(event) {
console.log('Input lost focus');
});
focusin
The focusin
event is fired when an element is about to gain focus. The main difference between focusin
and focus
is that focusin
supports bubbling, whereas focus
does not.
document.addEventListener('focusin', function(event) {
console.log('Element is about to get focus');
});
focusout
The focusout
event is fired when an element is about to lose focus. The main difference between focusout
and blur
is that focusout
supports bubbling.
document.addEventListener('focusout', function(event) {
console.log('Element is about to lose focus');
});
Note: The
focusin
andfocusout
events fire before thefocus
andblur
events respectively. Also, thefocusin
andfocusout
events bubble, while thefocus
andblur
events do not.
HashChange Event
hashchange
The hashchange
event is fired when the fragment identifier of the URL (the part of the URL beginning with and following the #
) changes.
window.addEventListener('hashchange', function(event) {
console.log('Hash changed to: ' + location.hash);
});
Input Events
input
This event is fired when the value of an <input>
, <select>
, or <textarea>
element has been changed.
let inputElement = document.querySelector('input');
inputElement.addEventListener('input', function(event) {
console.log('Input value changed to: ' + event.target.value);
});
Keyboard Events
These events handle interactions with the keyboard.
keydown
The keydown
event is fired when a key is pressed down.
document.addEventListener('keydown', function(event) {
console.log('Key down: ' + event.key);
});
keyup
The keyup
event is fired when a key is released.
document.addEventListener('keyup', function(event) {
console.log('Key up: ' + event.key);
});
keypress
The keypress
event is fired when a key that produces a character value is pressed down. This event is deprecated.
document.addEventListener('keypress', function(event) {
console.log('Key press: ' + event.key);
});
Note: For the keypress
event, non-character keys (like “F1” or “Home”) do not trigger the event in some browsers. The keydown
and keyup
events provide a code indicating which key is pressed, while keypress
indicates which character was entered.
Mouse Events
click
The click
event is fired when a pointing device button (usually a mouse’s primary button) is pressed and released on a single element.
document.addEventListener('click', function(event) {
console.log('Clicked at coordinates: ' + event.clientX + ', ' + event.clientY);
});
dblclick
The dblclick
event is fired when a pointing device button (such as a mouse’s primary button) is double-clicked on a single element.
document.addEventListener('dblclick', function(event) {
console.log('Double clicked at coordinates: ' + event.clientX + ', ' + event.clientY);
});
The contextmenu
event is fired when the right button of the mouse is clicked (before the context menu is displayed), or when the context menu key is pressed.
document.addEventListener('contextmenu', function(event) {
console.log('Right click or context menu key pressed at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mousedown
The mousedown
event is fired when a pointing device button is pressed on an element.
document.addEventListener('mousedown', function(event) {
console.log('Mouse button pressed at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mouseup
The mouseup
event is fired when a pointing device button is released over an element.
document.addEventListener('mouseup', function(event) {
console.log('Mouse button released at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mousemove
The mousemove
event is fired when a pointing device is moved while it is over an element.
document.addEventListener('mousemove', function(event) {
console.log('Mouse moved to coordinates: ' + event.clientX + ', ' + event.clientY);
});
mouseover
The mouseover
event is fired when a pointing device is moved onto the element that has the listener attached or onto one of its children.
document.addEventListener('mouseover', function(event) {
console.log('Mouse over at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mouseout
The mouseout
event is fired when a pointing device (usually a mouse) is moved off the element that has the listener attached or off one of its children.
document.addEventListener('mouseout', function(event) {
console.log('Mouse out at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mouseenter
The mouseenter
event is fired when a pointing device (usually a mouse) is moved onto the element that has the listener attached.
document.addEventListener('mouseenter', function(event) {
console.log('Mouse enter at coordinates: ' + event.clientX + ', ' + event.clientY);
});
mouseleave
The mouseleave
event is fired when the pointer of a pointing device (usually a mouse) is moved out of an element that has the listener attached.
document.addEventListener('mouseleave', function(event) {
console.log('Mouse leave at coordinates: ' + event.clientX + ', ' + event.clientY);
});
Note: Each of these events provides a MouseEvent
object which contains information about the mouse interaction, including the position of the mouse, which buttons were pressed, which modifiers keys were held down (Shift, Control, Alt, Meta), and more.
PageTransition Events
PageTransition events handle interactions when a user navigates to or from a webpage.
pageshow
The pageshow
event is fired when a session history entry is being traversed to. This could happen either when the page is loaded directly without a previous session history entry, or when the page is being visited again, with a session history entry.
window.addEventListener('pageshow', function(event) {
console.log('Page shown: ' + document.location.href);
});
pagehide
The pagehide
event is fired when a session history entry is being traversed from. This could happen either when the page is going away, or when the page is being hidden in a prerendering process.
window.addEventListener('pagehide', function(event) {
console.log('Page hidden: ' + document.location.href);
});
Note: Each of these events provides a PageTransitionEvent
object which contains information about the page transition, including whether the page was cached or not.
Popstate Event
popstate
The popstate
event in JavaScript is fired when the active history entry changes while the user navigates the session history. This can happen due to back or forward buttons being clicked or when the user clicks a link that was previously visited.
window.addEventListener('popstate', function(event) {
console.log('Location: ' + document.location + ', state: ' + JSON.stringify(event.state));
});
Progress Events
loadstart
The loadstart
event in JavaScript is fired when the browser starts loading video data.
var vid = document.getElementById("myVideo");
vid.onloadstart = function() {
console.log('Video loading started');
};
error
The error
event gets triggered when an error occurs while loading an external file or a script. This can be very useful for error handling and debugging, as it can provide information about what went wrong.
var img = new Image();
img.onerror = function() {
alert('Error occurred while loading image');
};
img.src = 'path_to_image.jpg';
In this case, if there’s an error loading the image (perhaps because the path is incorrect), the onerror
function will be called, and an alert will be shown.
It’s important to note that not all errors trigger the error
event. For instance, syntax errors in your JavaScript code won’t trigger the error
event. It’s mainly used for handling errors related to loading external resources.
Storage Event
storage
The storage
event is triggered when changes are made to the localStorage
or sessionStorage
objects in the context of another document.
window.addEventListener('storage', function(e) {
console.log('Storage key "%s" in "%s" was changed from "%s" to "%s"', e.key, e.storageArea, e.oldValue, e.newValue);
});
The storage
event is fired on the window object whenever setItem()
, removeItem()
, or clear()
is called and actually changes something in the localStorage
or sessionStorage
.
Remember, the
storage
event is only triggered when a window other than itself makes the changes. This means if you’re testing this in your browser, you’ll need two tabs or windows open to the same page.
Touch Events
Touch events in JavaScript allow you to handle interactions with a touch-sensitive device, such as a touchscreen. These events are similar to mouse events but support simultaneous touches at different locations on the touch surface.
touchstart
This event is fired when one or more touch points are placed on the touch surface.
element.addEventListener('touchstart', function(e) {
console.log('Touch started');
});
touchend
This event is fired when one or more touch points are removed from the touch surface.
element.addEventListener('touchend', function(e) {
console.log('Touch ended');
});
touchmove
This event is fired when one or more touch points are moved along the touch surface.
element.addEventListener('touchmove', function(e) {
console.log('Touch moved');
});
touchcancel
This event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
element.addEventListener('touchcancel', function(e) {
console.log('Touch cancelled');
});
Each of these events creates a TouchEvent
object, which contains a variety of data about the touch action, including the list of all the touch points (touches
), the touch points that changed in this event (changedTouches
), and more.
Transition Event
Transition events in JavaScript are related to CSS transitions. They allow you to handle the start and end of a transition on an element.
transitionend
This event is fired when a CSS transition has completed. In cases where a transition is removed before completion, such as if the CSS transition-property
is removed, then the event will not be triggered.
element.addEventListener('transitionend', function(e) {
console.log('Transition ended');
});
transitionstart
This event is fired when a CSS transition starts. Note that this event is not widely supported, and it’s not recommended to use it in production code.
element.addEventListener('transitionstart', function(e) {
console.log('Transition started');
});
transitioncancel
This event is fired when a CSS transition is cancelled. Similar to transitionstart
, this event is not widely supported and not recommended for production code.
element.addEventListener('transitioncancel', function(e) {
console.log('Transition cancelled');
});
UI Events
The UI events are related to actions done from the user interface.
abort
The abort
event occurs when the loading of an audio/video or an image is aborted.
var img = new Image();
img.addEventListener('abort', function(e) {
console.log('Process aborted');
});
beforeunload
The beforeunload
event is fired just before the window is about to unload its resources. It can be used to ask for confirmation before navigating away from a page.
window.addEventListener('beforeunload', function(e) {
e.preventDefault();
e.returnValue = '';
});
load
This load
event is fired when a resource and its dependent resources have finished loading. It’s commonly used to execute code when a page has fully loaded.
window.addEventListener('load', function(e) {
console.log('Window loaded');
});
resize
The resize
event is fired when the document view has been resized.
window.addEventListener('resize', function(e) {
console.log('Window resized');
});
scroll
The scroll
event is fired when the document view or an element has been scrolled.
window.addEventListener('scroll', function(e) {
console.log('Window scrolled');
});
select
This event is fired after some text has been selected in an element.
element.addEventListener('select', function(e) {
console.log('Text selected');
});
unload
This event is fired once a page has unloaded (or the browser window has been closed). However, it’s recommended to use the beforeunload
event instead.
window.addEventListener('unload', function(e) {
console.log('Window unloaded');
});
Wheel Event
wheel
The wheel
event is fired when the user rotates a wheel button on a pointing device, typically a mouse. This event can be used to handle both horizontal and vertical scrolling.
element.addEventListener('wheel', function(e) {
console.log('Wheel scrolled');
});
This event can also be triggered by touchpad interactions. In some browsers, it may return different values for the delta, i.e., the amount of rotation.
Miscellaneous Events
afterprint
This event fires when a page has started printing or the print preview has been closed. It can be used to revert any changes made to the document to prepare it for printing.
window.onafterprint = function(){
alert("You have printed this document.");
}
beforeprint
This event fires just before a document starts to print or the print preview opens. It’s a good time to apply specific styles for printing.
window.onbeforeprint = function(){
alert("You are about to print this document.");
}
canplay
This event occurs when the browser has loaded enough of the media file to start playing it. This event is often used to remove loading animations or buffering messages.
var vid = document.getElementById("myVideo");
vid.oncanplay = function() {
alert("Can start playing video");
};
canplaythrough
This event fires when the browser estimates it can play the media file without having to stop for buffering, given the current download speed.
var vid = document.getElementById("myVideo");
vid.oncanplaythrough = function() {
alert("Can play through video without stopping");
};
change
The change event triggers when an input, select, or textarea element has its value or state changed by the user.
var input = document.getElementById("myInput");
input.onchange = function(){
alert("The content has changed.");
}
ended
The ended event fires when audio or video playback has completed to the end of the media.
var vid = document.getElementById("myVideo");
vid.onended = function() {
alert("The video has ended.");
};
fullscreenchange
This event fires when transitioning in or out of fullscreen mode. This could be in response to a user clicking a fullscreen button or a JavaScript call to requestFullscreen()
.
document.addEventListener("fullscreenchange", function() {
if (document.fullscreenElement) {
alert("Full screen mode entered!");
} else {
alert("Full screen mode exited!");
}
});
fullscreenerror
This event fires when the browser cannot switch to fullscreen mode in response to a request from a script, such as if the request was made in a sandboxed iframe.
document.onfullscreenerror = function() {
alert("An error occurred while trying to switch to fullscreen.");
};
invalid
This event fires when a submittable element does not satisfy its validation constraints, preventing form submission.
var input = document.getElementById("myInput");
input.oninvalid = function(event) {
event.target.setCustomValidity('Enter some text.');
};
loadeddata
This event fires when the browser has loaded the current frame of an audio or video, but not enough to play next frame of the media.
var vid = document.getElementById("myVideo");
vid.onloadeddata = function() {
alert("The media data has been loaded.");
};
loadedmetadata
This event triggers when the browser has loaded meta data for the audio or video, such as its duration and dimensions (for video).
var vid = document.getElementById("myVideo");
vid.onloadedmetadata = function() {
alert("Metadata for the video has been loaded.");
};
message
The message event is fired when a window or worker receives a message.
window.addEventListener('message', function(event) {
alert("Received message: " + event.data);
}, false);
offline
The offline event fires when the browser has lost access to the network and the value of navigator.onLine switches to false.
window.addEventListener('offline', function() {
alert("You are now offline.");
});
online
The online event fires when the browser has gained access to the network and the value of navigator.onLine switches to true.
window.addEventListener('online', function() {
alert("You are back online.");
});
open
This event is fired when a connection with a web socket or an event source is established.
var evtSource = new EventSource("ssedemo.php");
evtSource.onopen = function() {
alert("Connection to server opened.");
};
pause
The pause event is fired when audio or video playback has been paused, either by the user or programmatically.
var vid = document.getElementById("myVideo");
vid.onpause = function() {
alert("The video has been paused.");
};
play
The play event fires when audio or video playback has been started or is no longer paused.
var vid = document.getElementById("myVideo");
vid.onplay = function() {
alert("The video has started playing.");
};
playing
The playing event fires when audio or video playback is ready to start after having been paused or delayed due to buffering.
var vid = document.getElementById("myVideo");
vid.onplaying = function() {
alert("The video is playing.");
};
progress
The progress event is fired periodically when a request is in progress and browser is receiving data.
var vid = document.getElementById("myVideo");
vid.onprogress = function() {
alert("Downloading video data...");
};
ratechange
The ratechange event is fired when the playback speed of a video or audio is changed.
var vid = document.getElementById("myVideo");
vid.onratechange = function() {
alert("The playback rate has changed.");
};
reset
The reset event fires when a form is reset, either by a script or by clicking a reset button.
var form = document.getElementById("myForm");
form.onreset = function(){
alert("The form has been reset.");
}
search
The search event fires when a search input field receives user input and the user presses the “Enter” key or clicks the search button in the search field.
var input = document.getElementById("mySearch");
input.onsearch = function(){
alert("You searched for: " + input.value);
}
seeked
The seeked event fires when a seek operation completed, the current playback position has been moved to a new position.
var vid = document.getElementById("myVideo");
vid.onseeked = function() {
alert("Seeking has ended.");
};
seeking
The seeking event fires when a seek operation began in an audio or video.
var vid = document.getElementById("myVideo");
vid.onseeking = function() {
alert("Seeking has started.");
};
show
Occurs when a <menu>
element is shown as a context menu. The show
event is not widely supported across all browsers.
<!-- Note: The 'show' event is not widely supported -->
<menu type="context" id="mymenu">
<button label="Refresh" onclick="location.reload()">
</menu>
<p contextmenu="mymenu">Right-click to display context menu</p>
<script>
var menu = document.getElementById('mymenu');
menu.addEventListener('show', function () {
alert('Context menu is shown.');
});
</script>
stalled
The stalled event fires when the browser is trying to fetch media data, but data is unexpectedly not forthcoming.
var vid = document.getElementById("myVideo");
vid.onstalled = function() {
alert("The video is stalled due to unavailable data.");
};
submit
The submit event fires when a form is submitted. It only applies to the <form>
element.
var form = document.getElementById("myForm");
form.onsubmit = function(){
alert("The form has been submitted.");
}
suspend
The suspend event fires when media data loading has been suspended.
var vid = document.getElementById("myVideo");
vid.onsuspend = function() {
alert("Data loading has been suspended.");
};
timeupdate
The timeupdate event is fired when the time indicated by the currentTime attribute of a video or audio has been updated.
var vid = document.getElementById("myVideo");
vid.ontimeupdate = function() {
alert("The playing position has changed.");
};
toggle
The toggle event fires when the open attribute of a <details>
element changes, indicating that its contents have been shown or hidden.
var det = document.getElementsByTagName("details")[0];
det.ontoggle = function() {
if (det.open) {
alert("Details have been expanded.");
} else {
alert("Details have been collapsed.");
}
};
waiting
The waiting event fires when playback has stopped because of a temporary lack of data.
var vid = document.getElementById("myVideo");
vid.onwaiting = function() {
alert("The video is waiting to be resumed.");
};
volumechange
The volumechange event fires when the volume of a video or audio has been changed, including when the sound has been muted or unmuted.
var vid = document.getElementById("myVideo");
vid.onvolumechange = function() {
alert("The volume has been changed.");
};