Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Mouse pointer when ajax call

I want to change the mouse pointer to the "Wait" symbol when we run the AJAX call and return back to default pointer after completing the call. I have tried as follows but my problem is it's just working on Firefox until I dont click/press the mouse button. Here is my code:

function initializeAjax(url){
    $('html, body').css("cursor", "wait");

    try {
        if (url.substring(0,4) == ".mdf") {
            var database = window.location.pathname.slice(0,window.location.pathname.lastIndexOf('.mdf'));
            var url = database + url;
        }

        initRequest(url);
        returnedValues = null;
        req.onreadystatechange = returnedValues;
        nocache = Math.random();
        req.open("GET", url+"&nocache = "+nocache, false);
        req.send(null);

        $('html, body').css("cursor", "auto");
        return req.responseText;
    }
    catch(err) {
        return "Error 8";
    }
}

Could anyone please help how to change above to solve the problem soo that it shud work in Firefox and IE too.

like image 448
Somi Meer Avatar asked Jan 10 '12 15:01

Somi Meer


3 Answers

As of jQuery 1.9, this is how this can be done:

$(document).ajaxStart(function ()
{
    $('body').addClass('wait');

}).ajaxComplete(function () {

    $('body').removeClass('wait');

});

CSS

body.wait *, body.wait
{
    cursor: progress !important;
}
like image 140
Leniel Maccaferri Avatar answered Nov 08 '22 14:11

Leniel Maccaferri


Have a look at the jQuery get method. It's very simple to use and handles callback as well, so you'll have no problem adding the code to set the mouse cursor back...

http://api.jquery.com/jQuery.get/

Example...

$('html, body').css("cursor", "wait");
$.get("yourajaxcall.url", function(data) {
    $('html, body').css("cursor", "auto");

    //  Success - do something with "data" here

}).error(function() {
    $('html, body').css("cursor", "auto");

    //  There was an error - do something else

});
like image 37
Reinstate Monica Cellio Avatar answered Nov 08 '22 14:11

Reinstate Monica Cellio


This post here has a great solution for the problem.

Here's his solution:

function globalAjaxCursorChange() 
{
  $("html").bind("ajaxStart", function(){
     $(this).addClass('busy');
  }).bind("ajaxStop", function(){
     $(this).removeClass('busy');
  });
}

And then in the CSS:

html.busy, html.busy * {  
  cursor: wait !important;  
}  

I like the CSS approach and toggling a class rather than actually changing the CSS in the Javascript. Seems like a cleaner approach to me.

To apply this to your code specifically, you would change the Javascript that is trying to change the cursor to just $(this).addClass('busy'); then when you want to change the cursor back just call $(this).removeClass('busy');

like image 6
Joel Avatar answered Nov 08 '22 14:11

Joel