[javascript] How to hide element using Twitter Bootstrap and show it using jQuery?

Let's say I create an HTML element like this,

<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>

How could I show and hide that HTML element from jQuery/Javascript.

JavaScript:

$(function(){
  $("#my-div").show();
});

Result: (with any of these).

I would like the elements above to be hidden.

What is simplest way to hide element using Bootstrap and show it using jQuery?

This question is related to javascript jquery html css twitter-bootstrap

The answer is


Twitter Bootstrap provides classes for toggling content, see https://github.com/twbs/bootstrap/blob/3ee5542c990817324f0a07b97d01d1fe206fd8d6/less/utilities.less.

I'm completely new to jQuery, and after reading their docs I came to another solution to combine Twitter Bootstrap + jQuery.

First, the solution to 'hide' and 'show' an element (class wsis-collapse) when clicking on another element (class wsis-toggle), is to use .toggle.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle();
    });
});

You already have hidden the element .wsis-collapse by using Twitter Bootstrap (V3) class .hidden also:

.hidden {
  display: none !important;
  visibility: hidden !important;
}

When you click on .wsis-toggle, the jQuery is adding an inline style:

display: block

Because of the !important in the Twitter Bootstrap, this inline style has no effect, so we need to remove the .hidden class, but I won't recommend .removeClass for this! Because when jQuery is going to hide something again, it's also adding an inline style:

display: none

This is not the same as the .hidden class of Twitter Bootstrap, which is optimized for AT as well (screen readers). So, if we want to show the hidden div, we need to get rid of the .hidden class of Twitter Bootstrap, so we get rid of the important statements, but if we hide it again, we want to have the .hidden class back again! We can using [.toggleClass][3] for this.

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden" );
    });
});

This way you keep using the hidden class every time the content is hidden.

The .show class in TB is actually the same as the inline style of the jQuery, both 'display: block'. But if the .show class at some point will be different, then you simply add this class as well:

jQuery(document).ready(function() {
    jQuery(".wsis-toggle").click(function(){
        jQuery(".wsis-collapse").toggle().toggleClass( "hidden show" );
    });
});

I solved my issue by editing the Bootstrap CSS file, see their doc:

.hide:

.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1

.hide {
  display: none !important;
}

.hidden is what we're suppose to use now, but it is actually:

.hidden {
  display: none !important;
  visibility: hidden !important;
}

The jQuery "fadeIn" won't work because of the "visibility".

So, for the latest Bootstrap, .hide is no longer in use, but it's still in the min.css file. so I left .hidden AS IS and just removed the "!important" from the ".hide" class ( which is supposed to be deprecated anyway ). but you can also just override it in your own CSS, I just wanted all my application to act the same so I changed the Bootstrap CSS file.

And now the jQuery "fadeIn()" works.

The reason that I've done this vs the suggestions above, is because when you "removeClass('.hide')" the object immediately is shown, and you skip the animation :)

I hope it helped others.


Use the following snippet for Bootstrap 4, which extends jQuery:

(function( $ ) {

    $.fn.hideShow = function( action ) {

        if ( action.toUpperCase() === "SHOW") {
            // show
            if(this.hasClass("d-none"))
            {
                this.removeClass("d-none");
            }

            this.addClass("d-block");

        }

        if ( action.toUpperCase() === "HIDE" ) {
            // hide
            if(this.hasClass("d-block"))
            {
                this.removeClass("d-block");
            }

            this.addClass("d-none");
      }

          return this;
    };

}( jQuery ));
  1. Put the above code in a file. Let's suppose "myJqExt.js"
  2. Include the file after jQuery has been included.

  3. Use it using the syntax

    $().hideShow('hide');

    $().hideShow('show');

hope you guys find it helpful. :-)


Razz's answer is good if you're willing to rewrite what you have done.

Was in the same trouble and worked it out with the following:

_x000D_
_x000D_
/**_x000D_
 * The problem: https://github.com/twbs/bootstrap/issues/9881_x000D_
 * _x000D_
 * This script enhances jQuery's methods: show and hide dynamically._x000D_
 * If the element was hidden by bootstrap's css class 'hide', remove it first._x000D_
 * Do similar in overriding the method 'hide'._x000D_
 */_x000D_
!function($) {_x000D_
    "use strict";_x000D_
_x000D_
    var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide};_x000D_
    $.fn.extend({_x000D_
        show: function() {_x000D_
            this.each(function(index) {_x000D_
                var $element = $(this);_x000D_
                if ($element.hasClass('hide')) {_x000D_
                    $element.removeClass('hide');_x000D_
                }_x000D_
            });_x000D_
            return oldShowHide.show.call(this);_x000D_
        },_x000D_
        hide: function() {_x000D_
            this.each(function(index) {_x000D_
                var $element = $(this);_x000D_
                if ($element.hasClass('show')) {_x000D_
                    $element.removeClass('show');_x000D_
                }_x000D_
            });_x000D_
            return oldShowHide.hide.call(this);_x000D_
        }_x000D_
    });_x000D_
}(window.jQuery);
_x000D_
_x000D_
_x000D_

Throw it away when Bootstrap comes with a fix for this problem.


Initiate the element with as such:

<div id='foo' style="display: none"></div>

And then, use the event you want to show it, as such:

$('#foo').show();

The simplest way to go I believe.


Update: From now on, I use .collapse and $('.collapse').show().


For Bootstrap 4 Alpha 6

For Bootstrap 4 you have to use .hidden-xs-up.

https://v4-alpha.getbootstrap.com/layout/responsive-utilities/#available-classes

The .hidden-*-up classes hide the element when the viewport is at the given breakpoint or wider. For example, .hidden-md-up hides an element on medium, large, and extra-large viewports.

There is also hidden HTML5 attribute.

https://v4-alpha.getbootstrap.com/content/reboot/#html5-hidden-attribute

HTML5 adds a new global attribute named [hidden], which is styled as display: none by default. Borrowing an idea from PureCSS, we improve upon this default by making [hidden] { display: none !important; } to help prevent its display from getting accidentally overridden. While [hidden] isn’t natively supported by IE10, the explicit declaration in our CSS gets around that problem.

<input type="text" hidden>

There is also .invisible which does affect the layout.

https://v4-alpha.getbootstrap.com/utilities/invisible-content/

The .invisible class can be used to toggle only the visibility of an element, meaning its display is not modified and the element can still affect the flow of the document.


hide and hidden are both deprecated and later removed, no longer exist in new versions. You can use d-none/d-sm-none/invisible etc classes depending on your needs. The probable reason they were removed is because hidden/hide is a bit confusing in the CSS context. In CSS, to hide (hidden) is used for visibility, not for display. visibility and display are different things.

If you need a class for visibility:hidden, then you need invisible class from visibility utilities.

Check below both visibility and display utilities:

https://getbootstrap.com/docs/4.1/utilities/visibility/

https://getbootstrap.com/docs/4.1/utilities/display/


Use bootstrap .collapse instead of .hidden

Later in JQuery you can use .show() or .hide() to manipulate it


Recently ran into this when upgrading from 2.3 to 3.1; our jQuery animations (slideDown) broke because we were putting hide on the elements in the page template. We went the route of creating name-spaced versions of Bootstrap classes that now carry the ugly !important rule.

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

In bootstrap 4 you can use d-none class to hide an element completely. https://getbootstrap.com/docs/4.0/utilities/display/


$(function(){

$("#my-div").toggle();

$("#my-div").click(function(){$("#my-div").toggle()})

})

// you don't even have to set the #my-div .hide nor !important, just paste/repeat the toggle in the event function.


HTML:

<div id="my-div" class="hide">Hello, TB3</div>

Javascript:

$(function(){
    //If the HIDE class exists then remove it, But first hide DIV
    if ( $("#my-div").hasClass( 'hide' ) ) $("#my-div").hide().removeClass('hide');

    //Now, you can use any of these functions to display
    $("#my-div").show();
    //$("#my-div").fadeIn();
    //$("#my-div").toggle();
});

?? The righter answer

In Bootstrap 4 you hide the element:

<p id="insufficient-balance-warning" class="d-none alert alert-danger">Pay me</p>

Then, sure, you could literally show it with:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').removeClass('d-none');
}

But if you do it the semantic way, by transferring responsibility from Bootstrap to jQuery, then you can use other jQuery niceties like fading:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').hide().removeClass('d-none').fadeIn();
}

This solution is deprecated. Use the top voted solution.

The hide class is useful to keep the content hidden on page load.

My solution to this is during initialization, switch to jquery's hide:

$('.targets').hide().removeClass('hide');

Then show() and hide() should function as normal.


Another way to address this annoyance is to create your own CSS class that does not set the !important at the end of rule, like this:

.hideMe {
    display: none;
}

and used like so :

<div id="header-mask" class="hideMe"></div>

and now jQuery hiding works

$('#header-mask').show();

Simply:

$(function(){
  $("#my-div").removeClass('hide');
});

Or if you somehow want the class to still be there:

$(function(){
  $("#my-div").css('display', 'block !important');
});

Based on the above answers, I have just added my own functions and this further doesn't conflict with the available jquery functions like .hide(), .show(), .toggle(). Hope it helps.

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

The method @dustin-graham outlined is how I do it too. Remember also that bootstrap 3 now uses "hidden" instead of "hide" as per their documentation at getbootstrap. So I would do something like this:

$(document).ready(function() {
    $('.hide').hide().removeClass('hide');
    $('.hidden').hide().removeClass('hidden');
});

Then whenever using the jQuery show() and hide() methods, there will be no conflict.


I like to use the toggleClass:

var switch = true; //it can be an JSON value ...
$("#my-div").toggleClass('hide', switch);

Bootstrap, JQuery, namespaces... What is wrong with a simple:

var x = document.getElementById('my-div');
x.className.replace(/\bhide\b/, ''); //remove any hide class
x.style.display = ''; //show
x.style.display = 'none'; //hide

You can create a little helper function, KISS compliant:

function mydisplay(id, display) {
    var node = (typeof id == 'string') ? document.getElementById(id) : id;
    node.className.replace(/\bhide\b/, '');
    if (node) {
        if (typeof display == 'undefined') {
            display = (node.style.display != 'none');
        } else if (typeof display == 'string' && display == 'toggle') {
            display = mydisplay(node, !mydisplay(node));
        } else {
            node.style.display = (display) ? '' : 'none';
        }
    }
    return display;
}
is_hidden = mydisplay('my-div'); //actual state
mydisplay('my-div', false); //hide
mydisplay('my-div', true); //show
mydisplay('my-div', 'toggle'); //toggle state

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation