Greetings, community. The following code adds a loaded class to body . How to change it so that the class is added two seconds after the condition is met (here - the DOM generation).

 function domReady() { document.body.className += " loaded"; } if (document.addEventListener) { document.addEventListener("DOMContentLoaded", function() { document.removeEventListener("DOMContentLoaded", arguments.callee, false); domReady(); }, false); } else if (document.attachEvent) { document.attachEvent("onreadystatechange", function() { if (document.readyState === "complete") { document.detachEvent("onreadystatechange", arguments.callee); domReady(); } }); } 

  • one
    setTimeout (function () {}, 2000) tried? - Roman Kozin
  • one
    @RomanKozin, to be honest - no. I have very tight scripts. Could you make an answer? This line looks like a logical solution. - malginovdesign Nov.
  • call your function in this setTimeout(function (){domReady();}, 2000); you can even write shorter setTimeout(domReady, 2000); - so it should also work - Ivan Karaman
  • @IvanmalginovdesignMalginov you are also one of those who think that java == javascript? - Alexey Shimansky
  • @ Alexey Shimansky never thought about it .. * shame * - malginovdesign

1 answer 1

Native JS :

 function ready(){ document.body.className += ' loaded' } document.addEventListener("DOMContentLoaded", function(event) { setTimeout(ready, 2000); }); 

jQuery

 $(function (){ setTimeout(function () { $('body').addClass('loaded') }, 2000); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

  • both options are wrong: the first parameter setTimeout must be a function. - Grundy
  • Dear, look carefully at the arguments instead of immediately putting a minus and run the code yourself - Roman Kozin
  • 2
    Exactly. after anonymous editing, the bugs are fixed. Before it was setTimeout(ready(), 2000); - which is obviously wrong. and minus is absolutely deserved. for advice that doesn't work. - Grundy