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)?
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.
To trigger an element's transition, toggle a class name on that element that triggers it. To pause an element's transition, use getComputedStyle and getPropertyValue at the point in the transition you want to pause it. Then set those CSS properties of that element equal to those values you just got.
onload and once the document is loaded remove the class to trigger all transition on all elements as specified in your css. Here is a reverse solution: Make your html layout and set the css accordingly to your final result (with all the transformation you want). Set the transition property to your liking.
Triggering transitions You can trigger CSS transitions directly with pseudo classes like :hover (activates when the mouse goes over an element), :focus (activates when a user tabs onto an element, or when a user clicks into an input element), or :active (activates when user clicks on the element).
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
Disable transitions on page load only:
<body class="js-stop-transition">
...
<script>document.body.classList.remove('js-stop-transition')</script>
</body>
And add to CSS:
body.js-stop-transition * { transition:none !important; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With