Skip to content

Instantly share code, notes, and snippets.

@arbaouimehdi
Created October 31, 2023 19:04
Show Gist options
  • Save arbaouimehdi/ccd31374f67e767a0bcefbc8a05aa7c3 to your computer and use it in GitHub Desktop.
Save arbaouimehdi/ccd31374f67e767a0bcefbc8a05aa7c3 to your computer and use it in GitHub Desktop.
Pauses or Play a video based on the tab's visibility status
/**
* Determines the browser-specific properties
* for detecting document visibility changes.
*/
function getVisibilityProperties() {
const mappings = {
hidden: "visibilitychange",
msHidden: "msvisibilitychange",
webkitHidden: "webkitvisibilitychange",
};
for (let prop in mappings) {
if (document[prop] !== undefined) {
return {
hidden: prop,
visibilityChange: mappings[prop],
};
}
}
return {
hidden: "hidden",
visibilityChange: "visibilitychange",
};
}
/**
* Handles the visibility change event.
*/
function handleVisibilityChange(e) {
e.stopPropagation();
const video = document.getElementById("video");
// Paused if visiting another tab
if (document.hidden) {
console.log(`⏸️ PAUSED at ${video.currentTime}`);
video.pause();
}
// Played if visiting another tab
else {
console.log(`▶ PLAYED from ${video.currentTime}`);
video.play();
}
}
/**
* Initializes event listeners after
* the DOM is fully loaded.
*/
function initializeEventListeners() {
const video = document.getElementById("video");
video.muted = false;
document.addEventListener(
visibilityChange,
handleVisibilityChange,
true
);
}
// Get visibility properties and set up event listeners.
const { hidden, visibilityChange } =
getVisibilityProperties();
document.addEventListener(
"DOMContentLoaded",
initializeEventListeners
);
<video
src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
height="100%" width="100%" id="video" autoplay muted controls loop>
</video>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment