Say you have page that has a bunch of transitions and animations on all sorts of elements. Some of them get triggered when the window is resized because they have to do with size of the page or position or padding or something. It doesn’t really matter what it is, the fact that the transition or animation runs may contribute to a feeling of jankiness as you resize the window. If those transitions or animations don’t deliver any benefit in those scenarios, you can turn them off!
The trick is to apply a class that universally shuts off all the transitions and animations:
let resizeTimer;
window.addEventListener("resize", () => {
document.body.classList.add("resize-animation-stopper");
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
document.body.classList.remove("resize-animation-stopper");
}, 400);
});
Now we have a resize-animation-stopper
class on the <body>
that can force disable any transition or animation while the window is being resized, and goes away after the timeout clears.
.resize-animation-stopper * {
animation: none !important;
transition: none !important;
}
There is probably some more performant way of doing this than setTimeout
, but that’s the concept. I use this right here on this very site (v17) after noticing some significant resizing jank. It hasn’t entirely eliminated the jank but it’s noticeably better.
Here’s an example:
See the Pen
Turn off animation on resize? by Chris Coyier (@chriscoyier)
on CodePen.
That demo is mostly just for the working code. There probably isn’t enough going on transitions-wise to notice much resize jank.
Would it not be preferable to set animation-play-state to paused?
Maybe? I guess if what is getting turned off is an actual
animation
it would start back up where it left off? Seems like a good idea. I think of that less, as I’d bet 95% of what I think of asanimation
in CSS is transitions.Rather than relying on setTimeout with an arbitrary time, can you not just re-activate the animation with a body:hover EventListener that is set with a resize event?
I created a CSS-only solution where
animation-play-state
gets activated on hover state of whole page wrapper. When the mouse is out of the window (e.g. during window resize) animation is stopped.