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
JavaScript
x
13
13
1
My JS
2
3
(function () {
4
$(document).on("click","#submitbutton", function (event) {
5
$(this).addClass('active');
6
var formdata = $("#filterdata").serializeArray();
7
var url1 = "/SelectUnit";
8
$.ajax({url: url1, data: formdata, type: 'GET', async:false ..}).done(function(){
9
$(this).removeClass('active');
10
11
})
12
});
13
})();
JavaScript
1
24
24
1
2
3
My CSS
4
5
6
.spinner {
7
display: inline-block;
8
opacity: 0;
9
max-width: 0;
10
11
-webkit-transition: opacity 0.25s, max-width 0.45s;
12
-moz-transition: opacity 0.25s, max-width 0.45s;
13
-o-transition: opacity 0.25s, max-width 0.45s;
14
transition: opacity 0.25s, max-width 0.45s; /* Duration fixed since we animate additional hidden width */
15
}
16
17
.has-spinner.active {
18
cursor:progress;
19
}
20
21
.has-spinner.active .spinner {
22
opacity: 1;
23
max-width: 50px; /* More than it will ever come, notice that this affects on animation duration */
24
}
JavaScript
1
6
1
My HTML
2
<div class="formbuttons">
3
<button type="button" id="submitbutton" class="btn buttoncolor has-spinner">
4
<span class="spinner"><i class="icon-spin icon-refresh"></i></span>Select</button>
5
<button type="button" class="btn buttoncolor" onclick="clearFilter();">Clear</button>
6
</div>
Advertisement
Answer
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);