简体   繁体   中英

Spinning wheel in jQuery

I am using following code to show a spinning wheel:

$("#loading")
.hide()
.ajaxStart(function(){

    $(this).show();
    setTimeout("3000");
})
.ajaxStop(function(){

    $(this).hide("slow");
})
;   

and:

<div id="loading">
            <img src="loading.gif" alt="Loading" />
</div>  

Problem: "setTimeout() is not working. And how can I display the image at the centre of webpage?"

setTimeout takes 2 paramter, the first one is the callback function and the second is the timeout in msec eg.

setTimeout(funcname,1000);

or

setTimeout(function(){
    //do stuff
},1000);

to display your image in center of the webpage you can use eg. this technique

#loading {
    position:absolute;
    top:50%;
    left:50%;
    width:100px;
    margin-left:-50px; //negative half of width
    height:80px;
    margin-top:-40px; //negative half of height
}
#loading {
   display: none;
   position: fixed;
   top: 48%;
   left: 48%
}

JS

$('#loading').ajaxStart(function(){
   var that = $(this)
    setTimeout(function() {
       that.show();
    }, "3000");
}).ajaxStop(function(){
    $(this).hide("slow");
})

I dont understand why you're using the timer, you can simply turn it on at start of ajax request, and then on success or error turn it off, like:

$('#loading').show();

$.post(url, request)

    .success(function(data) {
        $('#loading').hide();
        // Do what you want with data
    })

    .error(function(data) {
        $('#loading').hide();
        // Show error message
    });

To have your loading image in the middle of the page, make sure that it's container is within a 100% height parent, and if it is nested, make sure none of its parents are position:relative .

#loading {
    position:relative;
    width:100%;
    height:100%;
}

#loading img {
    margin-top: -12px; // Half images height;
    margin-left: -12px; // Half images width;
    position:absolute;
    top:50%;
    left:50%;
}

OR

#loading {
    width:100%;
    height:100%;
}

#loading img {
    width:24px // Images width
    height:auto; // If Image size changes don't mess with proportions
    margin:0 auto;
    margin-top:48%;
}

You use the SetTimeout function in a wrong way

setTimeout(function(){ 

// do sth

 }, 3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM