jquery - remove class based on condition

2021-6-21 anglehua

I am polling a json response for every 1 min and based on the response I am adding or removing overlay on my page. My response is most of the time positive , in this case , i should remove the overlay class. In the below code, else part is executing every time and remove class and hide functions are executed every time. Is there any way to avoid this . Is there any method in jquery to check whether class is added or not . Also hide is active or not. Or can anyone give syntax to achieve this by setting and unsetting a boolean variable.

(function poll() {
  setTimeout(function() {
      url: "path",
      type: "GET",
      success: function(data) {
        console.log("polling" + data);
        if (data.is_running === true) {
        } else {
          console.log("removing ....");

      dataType: "json",
      complete: poll,
      timeout: 200
  }, 5000);

You can use toggle() and toggleClass() with Boolean value no need of if...else statement otherwise returns false


And for checking that an element has a class or not you can use hasClass() which returns true if matched elements are assigned the given class

Try like below and keep the $() query methods in variable to make efficient !

var $overLay = $("#overlay"),
    $alertDiv = $("#alertDiv"),
    sh = 'show';

 if (data.is_running === true) {
 } else if ($overLay.hasClass(sh)) {
   $overLay.removeClass(sh );


Powered by emlog 京ICP备15036472号-3 sitemap