The problem is there is no general way to determine when an asynchronous call is done. You would need to set some kind of flag after the AJAX call (for example) is done and poll it with setInterval.
With synchronous functions, the browser probably won't update the display until the click handler is done anyways, so you would never see the active state. You can get around that by using setTimeout to remove the active class after 1/10 of a second. For this case, you could write a function like this:
function makeClickHandler(innerFunction) {
return function(event) {
var self = this;
$(self).addClass('active');
innerFunction.call(self, event);
window.setTimeout(function() {
$(self).removeClass('active');
}, 100);
}
}
You could then wrap any click handlers in the makeClickHandler function:
$(".button").click(makeClickHandler(function() { alert('clicked'); }));
Here's an example of how you could handle asynchronous events, but at this point, it might just be easier to add/remove the class in the individual event handlers.
function makeAsyncClickHandler(innerFunction) {
return function(event) {
var self = this;
$(self).addClass('active').data("done", false);
innerFunction.call(self, event);
var intervalID = window.setInterval(function() {
if ($(self).data("done")) {
$(self).removeClass('active');
window.clearInterval(intervalID);
}
}, 100);
}
}
The inner function would have to call
$(this).data("done", true);
when the asynchronous part is finished.
It would probably be easier to write "start" and "finish" functions that you can call on the element at the beginning of the function and after the event is finished.