Ayan Ayan - 2 months ago 14
Javascript Question

Checking the visibility of a div not working inside ajax success function

Well long story short, I am trying hide a div inside Ajax success function depending on whether its visible or not. But don't understand why it isn't working. I can set it to hide simply and which works but in the console when I check I find that it keeps on setting the div to

display:none
even if it is already hidden.

JS

$(document).ready(function() {
$('#loading').show();
setInterval(function () {
$.ajax({
type: "GET",
url: "generate_list.php",
success: function (result) {
//$('#loading').hide();
$('#loading:visible').hide();

if(result != '') {
$('#empty_storage').hide();
$('#file_list').html(result);
}
else {
$('#file_list').html('');
$('#empty_storage').show();
}
}
});
}, 1700);
});

Answer

Toggle visibility

   $(document).ready(function() {
        $('#loading').css('visibility': 'visible');
        setInterval(function () {
            $.ajax({
                type: "GET",
                url: "generate_list.php",
                success: function (result) {

                   if ($('#loading').css('visibility') == 'visible') {
                       $('#loading').css('visibility','hidden'); 
                    }

                    if(result != '') {
                        $('#empty_storage').hide();
                        $('#file_list').html(result);
                    }
                    else {
                        $('#file_list').html('');
                        $('#empty_storage').show();
                    }
                }
            });
        }, 1700);
    });

CSS : Initially loader will be hidden

#loading { 
   visibility : hidden;
 }

So go with visibility property if you want to check the visibility. But if you want to use .hide() or .show() then it depends on display property

Visibility : http://www.w3schools.com/cssref/pr_class_visibility.asp

Display : http://www.w3schools.com/cssref/pr_class_display.asp

Sample Demo : https://jsbin.com/jiluren/11/edit?html,css,js,output

Hope this helps. Thanks !