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

CSS from the parent page is not being applied to AJAX-injected content

I recently added AJAX functionality to a new website to dynamically load and insert Wordpress page content using AJAX. However, I encountered an issue where some CSS styles that were supposed to be loaded in the page head were not being applied. This resu ...

React Application - The division is positioned centrally when run on local host, however, it does not retain its center alignment

I'm encountering an issue with deploying my create-react-app on github pages. The first image showcases my deployed app on github pages, but the image is not properly centered on the page as intended. https://i.stack.imgur.com/rOciT.jpg On the othe ...

Upgrade to Rails 4 has resulted in a JavaScript/JQuery partial update that is only functioning properly for view.html.erb files with

Here is a controller example: class RuleSearchController < ApplicationController def index end def results # Rule is a simple AR class with just a name column @rules = Rule.all end end A search form exists in index.html.erb: <%= ...

The ngTagsInput autocomplete feature is not functioning properly and is failing to reveal

I'm having trouble getting the AutoComplete list to appear. My service returns a JSON model: TagID: 1, text:MyText but the AutoComplete list isn't showing up. Here's my HTML: <tags-input ng-model="tags" tag-class="{even: $index % 2 == 0, ...

Manually adjusting the aria-expanded attribute to "true" does not result in opening a new tab

After a certain condition is met, I want to open another tab. Below is my bootstrap navbar code along with the jQuery script. <ul class="nav navbar-default nav-justified" role="tablist" id="navbar"> <li role="presentation" class="active"><a ...

Utilizing just jQuery for a toolTip feature that showcases DIV content

Seeking to utilize jquery's toolTip for mouseover content, I aim to have it display DIV content instead of the usual title="...". My goal is to make this functionality modular... Here is my attempt at achieving this. However, I have encountered an is ...

Generate a visually dynamic representation of a live website page

I'm curious if it's possible to create a login page similar to the one shown in this image, using HTML, CSS, and Javascript. Instead of a traditional background image, I want the background to display the actual layout of another website, such a ...

The inline-block property can become unstable when dealing with a large number

When I create a parent container div with three child divs and set the display property to inline-block, everything looks great on jsfiddle CSS #container { border: 1px solid blue; padding: 2px; display: inline-block; } .child { width: ...

Executing an Ajax request from LocalHost to the MVC Controller within the same domain while utilizing KendoDataSource

Trying to retrieve data from an MVC controller located on an IIS Server within the domain is resulting in an error message: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:22205' ...

Move the width from left to right with animation

Currently, I am exploring ways to use jQuery to create an animation effect on a div where the width shrinks from left to right. My first step is to have the element animate as follows: Slide in from left to right Then continue moving to the right off th ...

How can you show a green check mark next to an input field in AngularJS after inputting valid data?

I am diving into the world of AngularJS and Angular Material with my web application. As a beginner in AngularJS and Angular Material, I need some help. My current task is to display a green checkmark next to an input field only when valid data is entere ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Cut off text inside an HTML anchor element using an ellipsis, while ensuring the image remains at the end - all without the need for JavaScript

How can I truncate link text on a header with an ellipsis but keep the image at the end as a glyphicon? And all of this without using JS. Here's my code: <!DOCTYPE html> <html> <body> <ul> <li> <a href="# ...

What is the process for retrieving the information sent from the client application to the jsreport server?

I want to create a downloadable pdf report through my angular application using jsreport. The client app makes a POST request passing sample data to the report server in this manner. $http.post('http://localhost:5488/api/report', { ' ...

Symfony's DataTables is encountering an issue with the JSON response, showing

I have encountered an issue while trying to fetch data from a response within my template table (using DataTables). The error message I receive is as follows: DataTables warning: table id=example - Invalid JSON response. For more information about this ...

Guide for implementing Ajax-based login functionality using Spring Security in a Grails and AngularJS application

I am currently working on developing a user form that utilizes Ajax requests to log in to the server. Within my Angular app, the POST function is structured like this: $http({ method: 'POST', url: '/j_spring_security_check', ...

Positioning elements in CSS relative to a specific div container

Looking for advice on how to position two images within a div using percentages relative to the parent div. Check out this fiddle for reference: http://jsfiddle.net/b9ce626s/ I experimented with setting position: absolute; on the image, but it seems to b ...

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

ClickEvent (or element selector) is experiencing functionality issues

I'm currently working on creating a small calculator using HTML, CSS, and JS. However, I'm facing an issue with selecting buttons of the calculator from the HTML script and adding EventListeners to them. Here is a snippet of my HTML code: `< ...