How to Continue Using Buttons with “data-loading-text” in Bootstrap 4 with jQuery

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 thinks 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 😉

Leave a Reply

Your email address will not be published. Required fields are marked *