Enhancing interactivity with jQuery's ajax event functionality

Alright, let me share my code with you:

$("#content_Div").ajaxStart(function () {
    $(this).css('cursor', 'wait')
}).ajaxComplete(function () {
    $(this).css('cursor', 'default')
});

I'm facing a simple issue: the cursor changes to the hourglass immediately on ajaxStart, but it doesn't switch back to default until I move the mouse. Interestingly, I found out that if you click after ajaxComplete, the cursor changes back to default. This happens because after ajaxComplete, clicking triggers the change in cursor, not just moving the mouse. What I really want is for the cursor to change without needing any extra clicks or movements.

My aim is to use the cursor as an indicator for when the request is finished.

Thank you in advance!

For Thomas:

function DF() { //Deletes selected File
if (selectedfiles.length == 0) {
    alert("No file selected!");
    return
};
var selectedtxt = (selectedfiles.length == 1) ? "'" + basename(selectedfiles[0]) + "'?" : 'these ' + selectedfiles.length + ' files?';
if (confirm("Are you sure you want to delete " + selectedtxt)) {
    $.each(selectedfiles, function () {
        $.post("server/editfile.php", {
            user: user,
            oper: "del",
            path: "../" + this
        }, function (res) {
            if (res) {
                alert(res);
            }
            else LT(dirHistory[current]);
        });
    })
}

}

Answer №1

It seems that the user must move the cursor to trigger a change, but there is another issue as well. If the user moves the cursor away from the #content_Div, they will not be able to see if the data is loading or not, since the CSS only applies when hovering over that specific DIV element.

An effective way to clearly indicate that data is being fetched, regardless of user interaction, is to use an animated gif, text like "Loading....", or both. This solution is less intrusive than altering the user's cursor.

One option is to append a loading image to the div where the data will appear when requested, and this image will disappear once the data has loaded. For example:

$("#content_Div").ajaxStart(function () {
    $("#content_Div").append('<img src="loading.gif" />');
});

In this scenario, ajaxStop is unnecessary because the loaded data takes the place of the image.

Here is a jsFiddle example using both an image and text for loading indication.

jsFiddle with multiple buttons and a loading div at the center of the page.

Answer №2

It has been five hours since I posted this question and no one has attempted to answer it yet. So, I will share what I have discovered.

This issue seems to be a bug specific to Google Chrome and Safari. Here is the link to the Chromium bug report.

In all other browsers, you can change the mouse cursor dynamically without requiring the user to click or move the mouse.

Unfortunately, this behavior contradicted my original intention of informing the user when a request was completed. If the user removed their hand from the mouse and waited for the cursor to change, they would wait indefinitely. There doesn't seem to be a fix for this as the bug remains unconfirmed according to the provided link. I couldn't find a workaround either, so here is what I ended up doing:

$("#content_Div").ajaxStart(function () {
    if(!$.browser.safari)//ignores ajaxStart if browser is safari or chrome
    $(this).css('cursor', 'wait')
}).ajaxComplete(function () {
    $(this).css('cursor', 'default')
});

Answer №3

I prefer handling it in a more refined manner:

$(document).ready(function(){  
  $("html").on("ajaxStart", function(){  
     $(this).addClass('busy');  
   }).on("ajaxStop", function(){  
     $(this).removeClass('busy');  
   });  
});

CSS:

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

Reference:

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

I'm trying to find a way to access a particular field within an HTML document using JavaScript in Node.js. Can anyone

<Response> <SMSMessageData> <Message>Delivered to 1/1 Total Cost: NGN 2.2000</Message> <Recipients> <Recipient> <number>+9109199282928</number> <cost>NGN 2.2000&l ...

What effect does setting div1 to float left have on the layout of div2 in css?

Behold the mystical code written in HTML. <div id="sidebar1"> sidebar1 </div> <div id="sidebar2"> sidebar2 </div> Beneath lies the enchanting CSS code for the aforementioned HTML structure. div { width: 100px; ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

White background with a black border and transparency on an Android device

I'm trying to create a shape that has a white background with a black border. <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shap ...

Is it possible to conceal an arrow in a typical dropdown menu?

Is it possible to conceal the arrow in a standard dropdown select fieldset? Check out this Fiddle for more information I am working on an autocomplete feature where users input an organization number and relevant information is fetched from a database. I ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

Alter the class of the div element every three seconds

Greetings, I trust everyone is doing well. I am in need of some assistance from your brilliant minds. I have a circular div along with three CSS classes, and my objective is to switch the div's class and update the label text every 3 seconds. Any insi ...

Using NextJs to pass a prop as a className

I'm having difficulty figuring out how to pass a prop to a className, and I'm questioning whether it's even possible. For instance, if the prop category is passed into the function as "category1", can I use styles.category in the ...

Automatically loading jQuery scripts from a webpage

I need some help with updating a page on my forum automatically whenever there is a new post. Unfortunately, the current script I have only seems to work on and off. I suspect that the issue may lie in the order of the 'success' and 'wait&a ...

Node.js AJAX post causing HTML page to not load properly

When using express.js, I want to be able to redirect to an HTML page after clicking on a table element. Currently, the output in the console.log is the HTML source instead of being redirected and interpreted as an HTML page. Here is my click function usin ...

What is the best way to eliminate the gap above a block element using CSS?

Currently in the process of designing a website, I am faced with a challenging issue that seems to have me stumped. The structure of my page consists entirely of HTML DIVs, with certain elements nested within their parent DIVs. My main dilemma lies in tryi ...

Displaying a Laravel variable in an Ajax callback to trigger a separate Ajax function

What I am attempting to accomplish here is quite complex. I aim to utilize one Ajax function across my website to manage information updates. Essentially, a universal update script that will trigger upon form submission. The challenge I am facing is that ...

Tips for displaying an image using the image tag in jQuery

I am looking to dynamically append a share button image after every image tag that meets certain criteria. For the code snippet and demonstration, you can visit this fiddler link here. $(document).ready(function() { $("img").each(function() ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

Changing the click event using jQuery

My JavaScript snippet is displaying a widget on my page, but the links it generates are causing some issues. The links look like this: <a href="#" onclick="somefunction()">Link</a> When these links are clicked, the browser jumps to the top of ...

Could one potentially use jQuery to navigate through JSON output?

My goal is to generate a JSON list that includes CSS classes and their respective URL records. Here's an example: var jsonList = [{ "CSSClass": "testclass1", "VideoUrl": "/Movies/movie.flv" }, { "CSSClass": "testclass2", "VideoUrl": "/Movies/ ...

Creating a custom button in PHP

Currently, I am in the process of developing a shopping cart feature. One key requirement is to send both the product ID and the desired quantity chosen by the user to another file named cart.php. Below is an excerpt from my code snippet: for($i=0;$i< ...

Utilize the HTML canvas to sketch on an image that has been inserted

I have a HTML canvas element within my Ionic application. <canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas> Within this canvas, I am loading an image. Below is the code snippet from the con ...

Is there a way to ensure a Javascript alert appears just one time and never again?

I struggle with Javascript, but I have a specific task that needs to be completed. I am participating in a school competition and need an alert to appear only once throughout the entire project, not just once per browsing session. The alert will inform ...

The previous method of using `vue/compiler-sfc ::v-deep` as a combinator has been phased out. Instead, opt for the new syntax `:deep(<

When developing with Nuxt 2, I am encountering numerous [@vue/compiler-sfc] ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead. errors when running npm run dev. After attempting to resolve the issue by changing a ...