Bharat Soni
Bharat Soni

Reputation: 2902

SetTimeout is not working in jquery

I am trying to add and remove a class on click event, it is something like highlight an element, but nothing is happing here :(. Here is my code: JQ:

var listed=($('.vis').size())-1,
btn=$('.compare-btn');
  listed < 5 ? listed>=2?btn.show(500):null):btn.text("more").addClass('border').setTimeout(btn.removeClass('border'),2000);

CSS:

.border{border:2px solid red;width:95%!important;}

please let me know what is wrong with this code

Upvotes: 0

Views: 1334

Answers (2)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276406

setTimeout is a built in JavaScript method, it's not a part of jQuery, see the MDN article about it.

Refactor

btn.text("more").addClass('border').setTimeout(btn.removeClass('border'),2000);

To:

btn.text("more").addClass('border');
setTimeout(function(){

    btn.removeClass('border');

},2000);

I also think that the ternary operator does not help your code very much. It's making it a bit un-readable. Please consider using the simpler if-else construct instead, especially if you're not using the return value.

If you'd like, you can use the jQuery .delay function to accomplish similar syntax to what you attempted like this. I suggest you keep using setTimeout though, it's simpler and native.

Upvotes: 5

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14882

setTimeout is not a jquery function. It needs to be on it's own line:

var listed=($('p').size())-1,
    btn=$('.compare-btn');
    if(listed < 5) {
      if(listed>=2) {
         btn.show(500);
      }
      else {
         null;
      }
    }
    else
    {
       btn.text("more").addClass('border');
    }
}

setTimeout(function(){btn.removeClass('border'); } ,2000);

Upvotes: 0

Related Questions