sparecycle
sparecycle

Reputation: 2058

Modify HTML button's classes with Javascript upon clicking when button already bound to JS event

Working on a slower, proprietary ecommerce platform and the client has requested that the call-to-action buttons on the site switch to spinner or loading animations after being clicked to reduce repeated submissions/clicks by the user. There is currently a good bit of delay between frontend interaction and backend results.

Almost all of the buttons are already bound to Javascript events to power their functionality. The loader animation is readily achievable by appending a new CSS class entitled "loading" to the button element.

HTML Button Example:

<button class="mz-button ui primary button" data-mz-action="next">Next</button>

HTML Button Example with Loading Animation:

<button class="mz-button ui primary button loading" data-mz-action="next">Next</button>

I think its best to avoid modifying the pre-existing Javascript methods/functions directly but what would be a "best practice" approach to append the "loading" class on button click but also ensure that the default button behavior is unaffected? From what I can tell, it seems that making use of this for specific button selection within the DOM might be smart.

As a secondary objective, it would be great if I could have this happen for any button site-wide.

Upvotes: 0

Views: 53

Answers (2)

Abhishek Dhanraj Shahdeo
Abhishek Dhanraj Shahdeo

Reputation: 1356

Yes, you are correct. Using this will remove the ambiguity of selections. You can avoid the modofication of pre-existing javascripts. Create new class names unique in the context that it doesn't coincide with others. Create custom functions and use them to serve your purpose. Use the classes with all your buttons and put them to work. If necessary make the use of the existing functions and don not forget to refactor. It will both speed up the site as well as help you in better understanding if the code written by you.

Upvotes: 0

Ashish Patel
Ashish Patel

Reputation: 941

you should create a function having a parameter of button element and other param which is needed by ajax. before the ajax call set the loader class to the button passed in parameter and as you get the response from server remove the loader class.

function eventhandler(ajaxParams,buttonObj){
    $(buttonObj).addClass("loader");
    jQuery.ajax({
          type: "post",
          url: url,
          data: ajaxParams,
          success: function(data) {
            $(buttonObj).removeClass("loader")
          },
          error: function(jqXHR,err) {
            $(buttonObj).removeClass("loader")
          }
      });
}

Upvotes: 1

Related Questions