Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Script Load Timing

If I have a button that sets off a jquery script is there a way to make sure the button is inactive until the script completes?

like image 338
dvancouver Avatar asked Mar 09 '09 05:03

dvancouver


People also ask

How to set loading time in jQuery?

See below for the code snippet: var start = new Date(); jQuery. ready(); var end = new Date(); var difference = (endTime - startTime) / 1000; alert("document. ready time: " + difference + " seconds");

Does jQuery affect performance?

However, there is a real negative performance impact from using jQuery, which is especially relevant when using it for the frontend of a website where it can harm end user experience.

Is jQuery slow?

jQuery is also far from fast loading. It is heavy and slows page loading down a lot. So it has to go and that means anything that uses jQuery has to go as well.


2 Answers

This is one area where I like to extend jQuery:

$.fn.disable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = true;
    });
}

$.fn.enable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = false;
    });
}

and then you can do:

$("#button").disable();
$("#button").enable();

I find myself disabling/enabling controls a lot.

like image 192
cletus Avatar answered Oct 11 '22 00:10

cletus


Somewhere at the beginning of your script (probably on the button's click event), set the button's disabled attribute to true:

$("#mybutton").attr("disabled", true);

Then, when complete, remove that attribute:

$("#mybutton").removeAttr("disabled");

EDIT:

If you want to get (slightly) fancy, change the text of the button while you're doing the work. If it's an image button, you can change the src to a friendly "please wait" message. Here's an example of the button text version:

$("#mybutton").click(function() {
  var origVal = $(this).attr("value");

  $(this).attr("value", "Please wait...");
  $(this).attr("disabled", true);

  //Do your processing.

  $(this).removeAttr("disabled");
  $(this).attr("value", origVal);
});
like image 23
Peter J Avatar answered Oct 10 '22 23:10

Peter J