Either of the other listed methods (.ajaxStart or $.ajaxSetup) will work fine to "globally" enhance ajax with that functionality, however I would suggest against this. EVERY call to $.ajax will get passed through those methods, including calls done by third party libraries. This might not be the desired behavior in the end.
If this were for any "large" project I would write my own $.ajax method that could be used anywhere I wanted that functionality, something like this:
(function ( $ ) {
var root = $('html');
function doAjax(options) {
var jqXHR = $.ajax(options);
if (options.disableSelection) {
root.addClass('busy');
options.disableSelection
.prop('disabled', true).addClass('animate-load')
jqXHR.always(function() {
root.removeClass('busy');
options.disableSelection
.prop('disabled', false).removeClass('animate-load');
});
}
return jqXHR;
}
window.doAjax = doAjax;
})(jQuery);
You can then replace $.ajax call that you want to have that functionality with doAjax instead of $.ajax and pass in your disableSelection: $('.element button').
You also get passed the options in the jQuery global events (.ajaxComplete and .ajaxStart) as well as in the beforeSend and complete as this if you take the $.ajaxSetup route.
Also, maybe take a look at $.ajaxPrefilter you get access to everything in there.
(function ($) {
// this value will never change, so why bother looking it up more than once
var root = $('html');
// we get to check the options of every $.ajax call, awesome!
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.disableSelection) {
root.addClass('busy');
options.disableSelection
.prop('disabled', true).addClass('animate-load');
jqXHR.always(function() {
root.removeClass('busy');
options.disableSelection
.prop('disabled', false).removeClass('animate-load');
});
}
});
})(jQuery);
// and then somewhere else when you make a call, pass disableSelection
$.ajax({
type: "post",
dataType: "json",
url: "/api/login",
// check out this method btw, it rules
data: $('.element form').serialize(),
disableSelection: $('.element button')
})
.done(function(data) {
// ....
});
Both methods have their advantages, though I tend to prefer the doAjax method because it makes it obvious that there are options to this method that standard jQuery.ajax doesn't provide. If you do decide to use a prefilter, and the code will be edited/worked on by multiple people, I highly suggest adding an obvious namespace to the disableSelection property, call it something like myCompanyDisableSelection so that someone can search the code base for that string rather than try reading jQuery documentation to figure out what the hell disableSelection does :)