user2127403
user2127403

Reputation: 43

Add class with setTimeout without Jquery

Is it possible to convert this jquery script to non-jquery script?

window.setTimeout(function(){$("#fullcontent").addClass("onload");}, 2100);

I would like to add class "onload" to the div called "fullcontent" with setTimeout of 2,1s.

Upvotes: 2

Views: 1771

Answers (2)

Hydrothermal
Hydrothermal

Reputation: 5081

Use of .querySelector() and .concat() are unnecessary and slower than the alternatives (GEBI and +=).

If you're sure that #fullcontent does not already have the class "onload", this will work fine:

setTimeout(function() {
    document.getElementById("fullcontent").className += " onload";
}, 2100);

The safer, cleaner way to avoid duplicate classes if #fullcontent may have already been given the "onload" class:

setTimeout(function() {
    var fullcontent = document.getElementById("fullcontent");

    if(fullcontent.className.indexOf("onload") === -1) {
        fullcontent.className += " onload";
    }
}, 2100);

If #fullcontent has no class whatsoever, you don't need to append and you can simply overwrite:

setTimeout(function() {
    document.getElementById("fullcontent").className = "onload";
}, 2100);

Upvotes: 0

Pabs123
Pabs123

Reputation: 3435

window.setTimeout(function() {
  document.querySelector('#fullcontent').className = "onload";
}, 2100);

Example: http://codepen.io/anon/pen/LGMKOJ

Edit: In case you don't want to overwrite the element's current class:

window.setTimeout(function() {
  var element = document.querySelector('#fullcontent');
  var className = element.className;
  element.className = className.concat(" onload");
}, 2100);

Upvotes: 3

Related Questions