I recently noticed on my blog that sometimes the CSS hover transitions for
color animate on page load. While this doesn’t impact the final design, it does make the
initial page load a bit of a stylistic mess.
I stumbled upon a great post on css-tricks that outlined a fix for this issue using jQuery. However, my goal for this site has always been keeping it as lean as possible. That's why I use Jekyll for static pages and minimal scripting (outside Disqus and Google Analytics). So of course I dug into how we can skip jQuery and just use ES6.
Here’s what the issue looks like:
The fix discussed in the above article goes like this. First we add a new class to the body (or could be html) element. This can be whatever you want. I called mine
.preload-transitions for extra readability.
Next we write a SCSS rule (you could also just use CSS here but I preferred SCSS for cleaning the rule up a bit) that ensures that all elements beneath the class above have their transitions disabled. And for extra assurance drop an
!important on them.
!important just means that we really, really want this value to be used over other inherited rules.
Lastly, we diverge from using jQuery and instead lean on ES6. First we’ll add an
event listener to the
DOMContentLoaded event (also known as page load). Next we
find the CSS class that disables the transitions
.preload-transitions. Lastly, once
we know the DOM element, we remove the class from it.
That’s it we’re done!
As far as browser support goes here’s some general notes with links to caniuse.com entries:
addEventListenerworks on all browsers except IE < 9 (link)
querySelectorhas similar support to
addEventListenerwith FireFox 2-3 also not supported (link)
classListhas partial support in IE and Opera (link)
Have another CSS transition trick or hack? Did this solution work for you? Tell me about it below.