While converting a Bootstrap 3 template design for use with Bootstrap 4, I noticed they removed stateful buttons (eg: “loading” and “reset” button states) from BS4! Granted it was mentioned in BS3, but I never noticed the deprecated warning 🙁
The deprecated code for showing a button’s loading state was $('#selector').button('loading')
and to return the button to its original state you would use $('#selector').button('reset')
.
I never realized how much I used stateful Bootstrap buttons until I was wrapping up the conversion with a page that makes heavy use of AJAX calls with LOTS of code-blocks like…
$.ajax({ ... beforeSend: function() { $('#selector').button('loading'); }, complete: function() { $('#selector').button('reset'); }, ... });
I realize certain features are modified/removed here and there from libraries like Bootstrap, but the functionality of the “button” plugin was invaluable to me and I cannot bear to part with it.
I came up with this simple jQuery plugin to retain use of stateful buttons…
// Loading button plugin (removed from BS4) (function($) { $.fn.button = function(action) { if (action === 'loading' && this.data('loading-text')) { this.data('original-text', this.html()).html(this.data('loading-text')).prop('disabled', true); } if (action === 'reset' && this.data('original-text')) { this.html(this.data('original-text')).prop('disabled', false); } }; }(jQuery));
You can of course use the jQuery plugin’s methods on any element, but buttons (links, etc) are likely more suitable IMO.
<button id="selector" data-loading-text="Loading...">Click Me</button>
Note: Uses html()
instead of text()
so you can include things like FontAwesome markup in data-loading-text
.
Having not checked the original Bootstrap/jQuery methods where this functionality was originally included, I have no idea if this is being done the same way as before. It was just a no-brainer way of achieving the same functionality.
Feel free to comment 😉
This saved me a ton of time when converting from BS3 to BS4. Thanks so much for sharing!
Thanks, this was quite helpful in migrating to BS4.
// Update 😉
(function($) {
$.fn.button = function(action) {
if (action === ‘loading’) {
if (this.data(‘loading-text’)) {
this.data(‘original-text’, this.html()).html(this.data(‘loading-text’)).prop(‘disabled’, true);
} else {
this.data(‘original-text’, this.html()).html(‘Loading…’).prop(‘disabled’, true);
}
} else if (action === ‘reset’ && this.data(‘original-text’)) {
this.html(this.data(‘original-text’)).prop(‘disabled’, false);
}
};
}(jQuery));
Bad idea to hard-code language directives into the script IMO. That’s why my example depends on button attributes. Same as the original implementation that was removed in BS4