I'm trying to show spinner on button while loading on submit, I have seen a couple of implementations and tried in my application but its not working. Here is the fiddle which I am trying to describe. I want to mention one other thing that this HTML is on my sidebar and being added through javascript on ajax call
My JS
(function () {
$(document).on("click","#submitbutton", function (event) {
$(this).addClass('active');
var formdata = $("#filterdata").serializeArray();
var url1 = "/SelectUnit";
$.ajax({url: url1, data: formdata, type: 'GET', async:false .....}).done(function(){
$(this).removeClass('active');
})
});
})();
My CSS
.spinner {
display: inline-block;
opacity: 0;
max-width: 0;
-webkit-transition: opacity 0.25s, max-width 0.45s;
-moz-transition: opacity 0.25s, max-width 0.45s;
-o-transition: opacity 0.25s, max-width 0.45s;
transition: opacity 0.25s, max-width 0.45s; /* Duration fixed since we animate additional hidden width */
}
.has-spinner.active {
cursor:progress;
}
.has-spinner.active .spinner {
opacity: 1;
max-width: 50px; /* More than it will ever come, notice that this affects on animation duration */
}
My HTML
<div class="formbuttons">
<button type="button" id="submitbutton" class="btn buttoncolor has-spinner">
<span class="spinner"><i class="icon-spin icon-refresh"></i></span>Select</button>
<button type="button" class="btn buttoncolor" onclick="clearFilter();">Clear</button>
</div>
You can use jQuery to replace the button thext once the button has been clicked. I used this on a previous project:
This replaced the actual button text with the spinning icon... You can change it back to the original text after the processing is done...
You can achieve this with the following code:
I made some changes (changed the icon and edited the CSS) in you code to be easier to test: http://jsfiddle.net/q1d06npq/4/
Instead of
$.ajax().done()
the best option in you case is to use the$.ajax().always()
that is executed even if the ajax fails.The code
$(this)
inside the callback function will not point to the button, to solve that you can use something like this:var elem = $(event.currentTarget);
the problem is that you're removing the active class before the code inside the $.ajax even executes.
There are several ways to pass in the (this) object to your $.ajax success function. here is one.
I found out the issue in my question. Actually I was doing
which is why 'adding the class' before the ajax call is being executed after the call.
I found out this from the following question.
jquery ajax beforesend