Temporarily Disable CSS Transitions | withoutTransition
👍🔥❤️😂😢😕
views
comments
Sometimes you need to temporarily disable CSS transitions. For example, when you want to change light/dark color-schemes and don't want a flashy transition.
That's why I created the withoutTransition
method. This method has the following features:
- Temporarily disable CSS transitions for the duration of the function call
- Utilizes several methods choosing the best one based on the clients browser
Method Definition
let timeoutAction;
let timeoutEnable;
// Perform a task without any css transitions
export const withoutTransition = (action: () => any) => {
// 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();
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 = setTimeout(() => {
action();
timeoutEnable = setTimeout(enable, 120);
}, 120);
};
Method Usage
withoutTransition(() => {
/* Your code here... */
});
You can see a full example of this method in action inside my article about disabling CSS transitions when changing color-schemes
References
👍🔥❤️😂😢😕
Comments
...
Loading comments...