Friday, September 12, 2014

Making jQuery and Boostrap 3 and "hide" class work together

One of the problems with using jQuery's show and hide methods is that they are not compatible with the provided Bootstrap css classes "show" and "hide".

What is the problem? Bootstrap's css class looks like this:



.hide {
  displaynone !important;
}

Those important styles are necessary on some elements to make the behavior as expected. However, jQuery doesn't overwrite them when setting css attributes with the built-in show/hide methods. The recommended way that I found is to manually use .addClass("hide") and .removeClass("hide")...which is way too annoying.



Add the following JavaScript code after the initial jQuery .js file load and all is well.

var originaljQueryShow = jQuery.fn.show;
var originaljQueryHide = jQuery.fn.hide;
jQuery.fn.extend({
    show: function () {
        var result = originaljQueryShow.apply(this, arguments);
        jQuery(this).removeClass("hide");
        return result;
    },
    hide: function () {
        var result = originaljQueryHide.apply(this, arguments);
        jQuery(this).addClass("hide");
        return result;
    }
});


This lets the original functionality of the jQuery show() and hide() to be maintained, while adding transparent support for the Bootstrap css hide class.