I have a div styled to have smooth transitions on background-color when hovered. This div is displayed in many pages (including homepage) but in homepage it has a different background-color.
div {
border:1px solid;
background-color:#fff;
display:inline-block;
width:100%;
height:100px;
-webkit-transition: 0.5s;
-moz-transition: 0.5s;
-o-transition: 0.5s;
transition: 0.5s;
}
div.homepage {
background-color:#777;
}
div:hover, div.homepage:hover {
background-color:#f00;
}
Since this div is included with a PHP snippet on each page, the idea (to keep code clean) is to output a generic div with PHP and then add a "homepage" class on homepage only, via jQuery.
$('div').addClass("homepage");
Unfortunately, this causes an undesired transition on page load (see fiddle, for sake of clarity click "Run" after loading). How can I disable CSS transitions on page load only, without affecting normal behaviour (when div is hovered)?
This is what worked for me:
http://css-tricks.com/transitions-only-after-page-load/
Essentially, you add a class to the body tag:
<body class="preload">
Which disables the transitions:
.preload * {
-webkit-transition: none !important;
-moz-transition: none !important;
-ms-transition: none !important;
-o-transition: none !important;
}
Then once the page has loaded you remove the class:
$(window).load(function() {
$("body").removeClass("preload");
});
Simples! :D
Would'n it be ok if you simply set the initial gray color for the div instead of white ?
Like this :
div {
border:1px solid;
background-color:#777;
display:inline-block;
width:100%;
height:100px;
-webkit-transition: 0.5s;
-moz-transition: 0.5s;
-o-transition: 0.5s;
transition: 0.5s;
}
See updated fiddle here : fiddle
The transition is forced when you dynamically add the class homepage
to the div
.
If the div
is loaded with the class
there is not any transition in load.
In your html:
<div class="homepage"></div>
Add the class in PHP before send it to client side.
Initially write only following properties
div {
border:1px solid;
background-color:#fff;
display:inline-block;
width:100%;
height:100px;
}
div.homepage {
background-color:#777;
}
div:hover, div.homepage:hover {
background-color:#f00;
}
after adding your homepage class, append remaining properties like this
var transProperty=$('<style>div { -webkit-transition: 0.5s; -moz-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; }</style>');
$('head').append(transProperty);