svelte-fancy-darkmode
Version:
A fancy dark mode toggle for Svelte
48 lines (47 loc) • 1.74 kB
JavaScript
// Original Source: https://reemus.dev/article/disable-css-transition-color-scheme-change#heading-ultimate-solution-for-changing-color-scheme-without-transitions
let timeoutAction;
let timeoutEnable;
// Perform a task without any css transitions
export function withoutTransition(action) {
if (typeof document === 'undefined') {
return;
}
// Clear fallback timeouts
clearTimeout(timeoutAction);
clearTimeout(timeoutEnable);
// Create style element to disable transitions
const style = document.createElement('style');
const css = document.createTextNode(`* {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}`);
style.appendChild(css);
// Functions to insert and remove style element
const disable = () => document.head.appendChild(style);
const enable = () => document.head.removeChild(style);
// Best method, getComputedStyle forces browser to repaint
if (typeof window.getComputedStyle !== 'undefined') {
disable();
action();
// eslint-disable-next-line ts/no-unused-expressions -- this is a side effect
window.getComputedStyle(style).opacity;
enable();
return;
}
// Better method, requestAnimationFrame processes function before next repaint
if (typeof window.requestAnimationFrame !== 'undefined') {
disable();
action();
window.requestAnimationFrame(enable);
return;
}
// Fallback
disable();
timeoutAction = window.setTimeout(() => {
action();
timeoutEnable = window.setTimeout(enable, 120);
}, 120);
}