Enable CSS transitions / transforms after pageload

March 6th, 2012

CSS transitions or transforms are triggered by user action like hovering or toggling classes.

To make CSS transitions occur at pageload we have  do a simple two step JavaScript trick: add a class and remove that class again to trigger the transition.

1. put this in the header of your page to add an extra class during loading

<script type="text/javascript">
document.documentElement.className += " js";
</script>

It will add js as a class to the html element.

2. Remove that extra class after pageload.

How?

with jQuery

$(document).ready(function(){

document.documentElement.className = ""

}

Without the  jQuery framework

document.addEventListener('DOMContentLoaded', function () {
document.documentElement.className = ""}, false);

or a very simple

setTimeout(function(){
document.documentElement.className = ""
},200);

In you CSS file make the transition

body{opacity:1;
transition:opacity 1s ease;}

.js body{opacity:0}

This approach has the advantage that no-javascript users see the final result (opacity 1) and will miss the transition.

Example:

Leave a Reply