Guide on altering the cursor icon during an AJAX operation within a JQuery dialog

When I have a JQuery dialog open and make some $.ajax calls, why can't I change the cursor?

I want to display a progress cursor while the code is processing so that users can see that the action is still ongoing. However, even though I update the CSS property to "cursor: progress", the browser UI does not reflect this change (tested on Firefox 23.0.1). Interestingly, the cursor changes if I remove the $.ajax calls and replace them with setTimeOut callbacks to simulate time passing. Any insights into what might be causing this issue? Thank you.

Below is the test code that replicates the problem:

$( "#dialog-confirm" ).dialog({

            resizable : true,
            height : 240,
            modal : true,

            buttons: {

                "Take Action": function() {

                        $( "body" ).css( 'cursor', 'progress' );

                        for ( i = 0; i < 2000; i++ ) 
                        {

                            $.ajax({
                                async : false,  
                                type : 'GET',
                                url : "test2.html", 
                                cache : false,
                                dataType: 'html',   
                                success : function(data) {
                                    $("#junk").append (data + "number: " + i);
                                },
                                error: function(data) {     

                                }
                            });

                        }

                        $( "body" ).css( 'cursor', 'default' );
                },

                "Exit": function() {
                    $( this ).dialog( "close" );
                }
            }
        });

Test page HTML:

<div id="dialog-confirm" title="Show Something here">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
        Text of the dialog box here
    </p>
</div>
<div id ="junk"> Some rubbish text so I can see the div </div>
<div>

The following is the HTML content loaded:

<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>

Edit: Further testing shows that the Dialog has no impact on the issue. The problem is related to JavaScript's single-threaded nature and the fact that the code is consuming processor without releasing it. Comments and answers received below have been helpful but haven't addressed my query directly. Modifying the code as follows:

var j = 0;  
var set = false;

{
    setTimeout(function doStuff () 
    {
        $.ajax({
            async   : false,  
            type    : 'GET',
            url     :  "test2.html", 
            cache   : false,
            dataType: 'html',   
            beforeSend: function () 
            {
                if (set === false)
                    { $("body").css('cursor', 'wait'); set = true; }
            },
            complete: function () {                        
            },

            success : function(data) {
                $("#junk").append(data + "number: " + ++j);      
                if (j === 1000) {
                    $("body").css('cursor', 'auto');
                }
            },
            error: function(data) {     
            }
        });

        if (j < 1000) {
            setTimeout(doStuff,20);
        }           

    }, 0);      
}

This solves the problem by relinquishing the processor after each $.ajax call. While not ideal, it seems to resolve the cursor issue;

Note: The for loop became redundant in this new test code, altering the original problem.

Answer №1

Here is a solution for you. Modify the css cursor using the beforeSend method and then revert it back to normal after processing with the complete method:

           $.ajax({
                async: false,
                type: 'GET',
                url: "example.html",
                cache: false,
                dataType: 'html',
                beforeSend: function () {
                    $("body").css({
                        'cursor': 'wait'
                    })
                },
                complete: function () {
                   $("body").css({
                        'cursor': 'default'
                    })
                },
                success: function (data) {
                    $("#output").append(data + "value: " + l);
                },
                error: function (data) {}
            });

Answer №2

Release the processor using setTimeout to allow the browser's UI to update the cursor.

setTimeout ( function executeFunction () 
{
    $.ajax({
        async   : false,  
        type    : 'GET',
        url     :  "test2.html", 
        cache   : false,
        dataType: 'html',   
        beforeSend: function () 
        {
            if ( flag === false )
                { $("body").css('cursor', 'wait'); flag = true; }
        },
        complete: function () {                        
        },

        success : function(data) {
            $("#junk").append ( data + "number: " + ++counter );      
            if ( counter === 1000 ) {
                $( "body" ).css( 'cursor', 'auto' );
            }
        },
        error: function(data) {     
        }
    });

    if ( counter < 1000 ) {
        setTimeout(executeFunction,20);
    }           

}, 0);      

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

HTML: Dealing with issues in resizing and resolution with floating elements on the left and right using

Encountering some issues with the HTML code below when resizing the window: 1: The right bar suddenly drops down if the width is made too small. 2: The spacing between the content and the right bar expands as the window width increases. <style ty ...

Example of jQuery UI tabs - each new tab opens with a unique script assigned

Here is a jQuery tabs script that you can check out: http://jqueryui.com/demos/tabs/#manipulation var $tabs = $( "#tabs").tabs({ tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ...

Prevent specific cells from being focused in ngGrid

Utilizing ngGrid to showcase data, I've encountered a dilemma with the cell templates. Some fields utilize a cell template to display an input field, while others do not. By using jQuery in my browser console, I attempted to remove the tabindex attri ...

The json data type seems to be malfunctioning when used in the jQuery ajax function

I am currently attempting to query the database and display the results using jQuery's ajax method. However, when I set the dataType property as json, it only logs the result that has a single object. Below is the code snippet: // Method triggered af ...

Differences in Loading Gif Visualization Across Chrome, Safari, and Firefox

Having an issue with a loading image in Chrome, while it displays correctly in Safari and Firefox. In Chrome, I see two half-loading images instead of one whole image. Struggling to find a solution for this problem, any assistance would be greatly apprecia ...

Making Jquery functions work with Internet Explorer (including toggle and animate)

Why is this jQuery code snippet not functioning as expected in Internet Explorer? It works flawlessly across all Webkit browsers. $('#logo').toggle(function() { $('#about').animate({'top': '-400px'},'slow&a ...

align the text to the left in the center of the page

.center { margin: 0 auto; display: table; } .center .content { display: table-cell; } These CSS styles are used to center align the container with the class .center, while also keeping its contents (in .content) left aligned: <div class="center" ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

Trouble with comparing two datetime values in JavaScript

I have a dilemma with two different appointments: appointment1 = "2013-07-08 12:30:00" appointment2 = "2013-07-08 13:30:00" My goal in JavaScript is to compare these two appointment dates. If they don't match, I want to remove the appointment; if t ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

Reloading a CodeIgniter page following an AJAX click action

I am currently facing an issue with my PHP CodeIgniter function code that is called by a jQuery AJAX function: $this->load->library('session'); $this->load->helper('url'); $ids = $_POS ...

Access the modal by simply clicking on the provided link

I have implemented a code snippet below to display data from MySQL in a modal popup. Everything is functioning correctly, but I am interested in triggering the modal by clicking a link instead of a button. Is it feasible to achieve this considering I have ...

Convert HTML table data to JSON format and customize cell values

Hey there, I have a HTML table that looks like this: <table id="people" border="1"> <thead> <tr> <th>Name</th> <th>Places</th> <th>Grade</th> </tr> & ...

jqote coming back as nothing

I am currently in the process of updating an HTML table with fresh data obtained through json and utilizing jQote. My jQote template is quite straightforward: <script type="text/html" id="template"> <![CDATA[ <tr> & ...

I am looking to incorporate a scroll feature into my form, as it is being displayed within a modal that is a separate component

Due to the size of my employee form exceeding the screen capacity, I need to incorporate a scroll property into my modal content. The form contains numerous fields that cannot be modified. Could you assist me in resolving the scrolling issue? Thank you! ...

Is it possible to line up two divs perfectly?

Hey there, I'm still trying to get the hang of CSS and using Dreamweaver CS6's fluid grid layout. In my attempt to create a header with two divs inside it - headerleft for an image and headerright for text - I've run into some alignment issu ...

jquery function that switches image after the fifth mouseover event

I just can't seem to figure this out. I need a mouseover event that switches between two images until the fifth time you mouseover, then it changes to a third image. Here is my code so far: <!doctype html> <html> <head> <meta c ...

The jQuery error message "e.nodeName is undefined" indicates a timeout issue

<script type="text/javascript"> var delayFunction = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); $(function() { $('#act ...