0

I need to create a generic function that I can apply to all my buttons that adds a loader image into the button by adding a class to the button when clicked and hides the image once whatever function the button triggered has returned.

How could I do this using jQuery?

This is the code I've got so far.

var B ={

    addSpinner: function () {
        $(this).click(function(){
            $(this).addClass('.spinner');
        });
    }
};

Am I using this correctly to select the clicked button? Would it be good practice to have another function to remove the class once the function the button triggered returned, or would it be better to have this in the addSpinner function? How do I listen for the that event?

Thanks

hyprstack
  • 4,043
  • 6
  • 46
  • 89
  • Please, add some details regarding what you have already tried. See jQuery references. It seems to be a quite common question (i.e. toggling css classes using jQuery). Have you already search similar question in SO? And, please, read the Stackoverflow [help page](http://stackoverflow.com/help/how-to-ask). – Alberto De Caro Oct 16 '14 at 10:22
  • possible duplicate of [Toggle between two classes in jQuery](http://stackoverflow.com/questions/1644545/toggle-between-two-classes-in-jquery) – Alberto De Caro Oct 16 '14 at 10:24

1 Answers1

0

Try making it a plugin

(function ( $ ) {
    $.fn.classToggler = function(cssClass) {
        $(this).click(function(){
            $(this).toggleClass(cssClass);
        });
        return this;
    };
}( jQuery ));

Now use it

$("#myButton").classToggler("spinner").click(function(){
    //do other stuff
});

Demo: http://jsbin.com/makoxibogeje/1/edit

AlexanderBrevig
  • 1,967
  • 12
  • 17