Skip to content

Instantly share code, notes, and snippets.

@oliverjam
Created January 27, 2021 12:30
Show Gist options
  • Save oliverjam/90bde61ca2f0b9141f3e4b0836ef0cbd to your computer and use it in GitHub Desktop.
Save oliverjam/90bde61ca2f0b9141f3e4b0836ef0cbd to your computer and use it in GitHub Desktop.
A simple Custom Element for autoplaying a video only if the user hasn't opted out of motion
// Wrap around a video you want to autoplay.
// Don't set the autoplay attribute,
// since that can't respect user preferences.
// e.g. <safer-autoplay><video src="vid.mp4"></video></safer-autoplay>
// Sidenote: motion should _really_ be opt-in,
// since lots of users won't know they can set a preference
// "no motion" is the safest default,
// but good luck getting that past your PO/designer ¯\_(ツ)_/¯
class SaferAutoplay extends HTMLElement {
connectedCallback() {
const video = this.querySelector("video");
// check if user opted out of motion
const motionQuery = window.matchMedia("(prefers-reduced-motion)");
// play/pause depending on preference
function checkMotion() {
motionQuery.matches ? video.pause() : video.play();
}
// check on first load
checkMotion();
// re-check when preferences change
motionQuery.addEventListener("change", checkMotion);
}
}
window.customElements.define("safer-autoplay", SaferAutoplay);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment