Reputation: 1045
I wrote the following script to allow me to create buttons which will execute an ajax request when you click them. After clicking it the script will add the class "btn-loading" to the button, disable it and when the ajax request is successful the script will change the button back to the original state.
Adding the class and adding the disabled attribute works fine on both jsfiddle and on my website, and I see no errors in the console.
The script:
jQuery.fn.extend({
loadingButton: function (options) {
return this.each(function () {
var btn = $(this);
btn.click(function () {
btn.addClass("btn-loading");
btn.attr('disabled','');
var ajaxCall = {
url: options.url,
type: options.type,
success: function (data) {
options.success(data);
btn.removeClass("btn-loading");
btn.removeAttr('disabled');
}
};
if (typeof (options.data) !== 'undefined') {
ajaxCall.data = options.data;
}
$.ajax(ajaxCall);
});
});
}
});
The usage:
$(document).ready(function () {
$("#loadButton").loadingButton({
url: "/echo/jsonp/",
success: function(data) {
console.log(data);
}
});
});
In the jsfiddle this works perfectly fine. But on my website it seems like only the background image doesn't change and it wont disable the button when you click it the first time, although clicking it the second time works fine.
I have tried searching for a solution, but if I don't know what the problem is, I don't know what to search for. Can anyone tell me what I'm doing wrong?
--EDIT
It seems to have something to do with the load time of the background image. When i add a button to the page which already has the "btn-loading" class and then click the button without the class, everthing works fine.
Upvotes: 0
Views: 192
Reputation: 1045
I found an article on css-tricks.com about preloading images:
One big reason to use image preloading is if you want to use an image for the background-image of an element on a mouseOver or :hover event. If you only apply that background-image in the CSS for the :hover state, that image will not load until the first :hover event and thus there will be a short annoying delay between the mouse going over that area and the image actually showing up.
This was probally the cause of my background image not showing up on the first click, because when I preload the background image, the button gets disabled and the background image is shown.
Upvotes: 1