2

Consindering the following simple example, I wonder why CSS3 transition effect is not triggered when using DOMContentLoaded? Using window.onload or document.onreadystatechange = "complete" will work!

I know that DOMContentLoaded does not wait for [style] but in that case i dont reference external stylesheets!

The most DomReady-Engines will fall back to DOMContentLoaded if supported! Maybe someone has some ideas or information about this issue for me! Thank you in advance!

EXAMPLE:

<!DOCTYPE html>
<html>
<head>
<script>
window.document.addEventListener('DOMContentLoaded', function() {
    var elem = window.document.getElementById('box1');
        elem.style.height = '400px';
        elem.style.transition = "height 1s ease-in";
}, false);
</script>
</head>
<body>
<div id="box1" style="display:block; background-color:green; position:absolute; width:400px; height:100px;" >Doesn't animate in IE, Opera, Chrome etc.. but often in FIREFOX</div>
</body>
</html>
Okyo
  • 357
  • 4
  • 17

2 Answers2

1

You should put the height change in a small setTimeout to assure that the transition property has applied when the line is ran

window.document.addEventListener('DOMContentLoaded', function() {
    var elem = document.getElementById('box1');
    elem.style.setProperty("transition", "height 1s ease-in");
    setTimeout(function() {
        elem.style.height = '400px';
    }, 10);
}, false);

Demo

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • thanx for your input, it worked with setTimeout! But why it does trigger with onload event? – Okyo May 12 '14 at 10:59
0

The MDN documentation says that the DOMContentLoaded event takes places without waiting for stylesheets:

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

The MDN documentation does not state that the stylesheets, images or subframes must be external. Apparently, the DOMContentLoaded event is fired even before the locally defined stylesheets are loaded.

It appears that using setTimeout() to delay setting the desired property by a short amount of time, such as 10 ms, is enough for a browser to complete loading of stylesheets in most cases. However, using setTimeout() is clearly not a reliable method to achieve your objective because there may be cases where the complete loading of all stylesheets may exceed the timeout specified in setTimeout().

Your transition works with window.onload or document.onreadystatechange because these events are fired upon the complete loading of the window or document, including stylesheets. Therefore, you may use something like this:

window.addEventListener('load', function() {
    var elem = window.document.getElementById('box1');
        elem.style.height = '400px';
        elem.style.transition = "height 1s ease-in";
}, false);
Beef Eater
  • 374
  • 3
  • 8