Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Created April 14, 2020 16:43
Show Gist options
  • Save nathansmith/b7ff56baae53183f4de3d41ca8dbce13 to your computer and use it in GitHub Desktop.
Save nathansmith/b7ff56baae53183f4de3d41ca8dbce13 to your computer and use it in GitHub Desktop.
How to enable (or disable) CSS animation via JS.
html:not([data-has-css-animation='true']) {
@include remove-css-animation;
}
@media (prefers-reduced-motion: reduce) {
@include remove-css-animation;
}
@mixin remove-css-animation {
*,
*:after,
*:before {
animation: none !important;
transition: none !important;
}
}
/*
Used like so…
```
import cssAnimation from './cssAnimation';
cssAnimation.init();
```
*/
// ==========
// Constants.
// ==========
const ATTR = 'data-has-css-animation';
const EVENT = 'DOMContentLoaded';
const FUNCTION = 'function';
const NO_PREFERENCE = '(prefers-reduced-motion: no-preference)';
const d = document.documentElement;
const w = window;
// ====================
// Set user preference.
// ====================
const setFlag = (media = {}) => {
// Get match.
const { matches } = media;
// Get bool.
const bool = !!matches;
// Set attribute.
d.setAttribute(ATTR, bool);
};
// =====================
// Remove event handler.
// =====================
const unbind = () => {
w.removeEventListener(EVENT, handleLoad);
};
// =====================
// Define event handler.
// =====================
const handleLoad = () => {
// Prevent doubles.
unbind();
// Has browser support?
if (typeof w.matchMedia === FUNCTION && typeof w.requestAnimationFrame === FUNCTION) {
// Wait for next frame.
w.requestAnimationFrame(() => {
// Get media.
const match = w.matchMedia(NO_PREFERENCE);
// Kickoff.
setFlag(match);
// Prevent doubles.
match.removeListener(setFlag);
// Add event.
match.addListener(setFlag);
});
}
};
// ==================
// Add event handler.
// ==================
const init = () => {
// Prevent doubles.
unbind();
// Add event.
w.addEventListener(EVENT, handleLoad);
};
// ==============
// Expose object.
// ==============
const cssAnimation = {
init,
unbind,
};
// =======
// Export.
// =======
export { cssAnimation };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment