Created
January 27, 2021 12:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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