'Disable CSS transitions on window resize?

I'm surprised I can't find any solutions to this. I've got four square divs which are in a line at full-screen, in a 2x2 grid at mobile size. They change colour with a CSS transition on click.

But when I resize my window, they float about the page into their new positions - an unwanted side effect of the CSS transition. I've tried using JQuery to toggle the transitions while resizing, which keeps them from floating, but there's a 50% chance that the transition class will be inactive when you stop resizing!

I've not put any code in here as it seems like such a simple problem. Does anybody have any simple solutions?



Solution 1:[1]

When the window resizing, we can add to < body > a special CSS-class "stop-transitions". After resizing and short timeout we removed this class. Put this before closing tag < body >:

<script>
    (function() { 
        const classes = document.body.classList;
        let timer = 0;
        window.addEventListener('resize', function () {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            else
                classes.add('stop-transitions');

            timer = setTimeout(() => {
                classes.remove('stop-transitions');
                timer = null;
            }, 100);
        });
    })();
</script>

And add next to your CSS. It resets the transition property for all during the resize. After resize and short timeout this class will removed and the transition works again.

body.stop-transitions * {
  transition: none !important;
}

Solution 2:[2]

If you use transition: all 200ms ease-out as opposed to transition: color 200ms ease-out you're applying transitions to all properties, instead of just one specific property.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Toby