0

I'm using a CSS class on the body to stop transitions running when the document loads. How can I remove it once the Window has loaded with JavaScript (no jQuery)?

HTML:

<body class="preload">

css:

.preload * {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -ms-transition: none !important;
  -o-transition: none !important;
}

This would be the jQuery equivalent *except I'm not using jQuery:

$("window").load(function() {
  $("body").removeClass("preload");
});
user3143218
  • 1,738
  • 5
  • 32
  • 48

2 Answers2

5

This should do the trick:

window.addEventListener(
    'load',
    function load()
    {
        window.removeEventListener('load', load, false);
        document.body.classList.remove('preload');
    },
    false);

Using addEventListener means that it won't interfere with any other event listeners that may be attached by other libs, etc.

The above code will remove the event listener once the event has fired too.

I would have thought the event listener should be on document but apparently that doesn't work.

Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
1

Something like this should work in all browsers:

window.onload = function () { document.body.className = ""; }

Drew's answer is good, but classList is not supported in older versions of IE as well as window.addEventListener, if that's important.

Max Al Farakh
  • 4,386
  • 4
  • 29
  • 56
  • True -- `classList` is a nice modern thing that you may not be able to use if your site is internet facing. You can set the empty string to `className` as you show instead if needed. – Drew Noakes Mar 30 '14 at 13:27