onvisibilitychange
onvisibilitychange Event
The onvisibilitychange
property serves as an event handler that triggers when a visibilitychange
event occurs on the document.
Syntax
Utilize the event name in methods such as addEventListener()
or by assigning it to an event handler property.
addEventListener("visibilitychange", (event) => {});
onvisibilitychange = (event) => {};
Example
Pausing Music When the Page Becomes Hidden
This example stops audio playback when the page is no longer visible and resumes it when the page becomes active again. For a complete example, refer to the Page Visibility API: Pausing Audio on Page Hide documentation.
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
playingOnHide = !audio.paused;
audio.pause();
} else {
// Resume playing if audio was "playing on hide"
if (playingOnHide) {
audio.play();
}
}
});
Sending session-end analytics when transitioning to a hidden state
This example considers the transition to a hidden state as the session's end and utilizes the Navigator.sendBeacon()
API to send the relevant analytics.
document.onvisibilitychange = () => {
if (document.visibilityState === "hidden") {
navigator.sendBeacon("/log", analyticsData);
}
};
Conclusion
The onvisibilitychange
event enables the execution of a function when a document's visibility state changes, determining whether the page is in the foreground or background. This is particularly useful for detecting when a user switches tabs or minimizes the browser, allowing you to adjust page behavior accordingly.
onreadystatechange
The onreadystatechange HTML event attribute defines a JavaScript function to run whenever the readyState property of an element changes, commonly used to monitor the progress of an XMLHttpRequest.
Drag-drop
HTML drag-and-drop event attributes manage interactions for dragging and dropping elements, allowing for interactive and dynamic content manipulation on web pages.