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() {
$.ajax({
url: "path",
type: "GET",
success: function(data) {
console.log("polling" + data);
if (data.is_running === true) {
$("#overlay").addClass('show');
$("#alertDiv").show();
} else {
console.log("removing ....");
$("#overlay").removeClass('show');
$("#alertDiv").hide();
}
},
dataType: "json",
complete: poll,
timeout: 200
})
}, 5000);
})();
jQuery removeClass() Method The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.
In jQuery, to replace one class properties with another, there is a function called replaceClass() through which it takes in two different class names the first class name is specified as a class which should be replaced with the second class name that is specified as the second parameter in the function, where it ...
You can use toggle()
and toggleClass()
with Boolean
value no need of if...else
statement otherwise returns false
$("#overlay").toggleClass('show',data.is_running);
$("#alertDiv").toggle(data.is_running);
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) {
$overLay.addClass();
$alertDiv.show(sh);
} else if ($overLay.hasClass(sh)) {
$overLay.removeClass(sh );
$alertDiv.hide();
}
You can check if an element has a specific class with hasclass()
:
var overlay = $('#overlay');
if (overlay.hasClass('show')) {
overlay.removeClass('show');
}
But you can use toggle()
and toggleClass()
, see Pranav's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With