0

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

Bharat Soni
  • 2,824
  • 6
  • 23
  • 48

2 Answers2

5

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.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

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);
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129