251
votes

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?

21
In order to keep this question relevant, I've modified it to work on both Bootstraps, because the answer is only a difference in class name.Evan Carroll

21 Answers

426
votes

The right answer

Bootstrap 4.x

Bootstrap 4.x uses the new .d-none class. Instead of using either .hidden, or .hide if you're using Bootstrap 4.x use .d-none.

<div id="myId" class="d-none">Foobar</div>
  • To show it: $("#myId").removeClass('d-none');
  • To hide it: $("#myId").addClass('d-none');
  • To toggle it: $("#myId").toggleClass('d-none');

(thanks to the comment by Fangming)

Bootstrap 3.x

First, don't use .hide! Use .hidden. As others have said, .hide is deprecated,

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

Second, use jQuery's .toggleClass(), .addClass() and .removeClass()

<div id="myId" class="hidden">Foobar</div>
  • To show it: $("#myId").removeClass('hidden');
  • To hide it: $("#myId").addClass('hidden');
  • To toggle it: $("#myId").toggleClass('hidden');

Don't use the css class .show, it has a very small use case. The definitions of show, hidden and invisible are in the docs.

// Classes
.show {
  display: block !important;
}
.hidden {
  display: none !important;
  visibility: hidden !important;
}
.invisible {
  visibility: hidden;
}
65
votes

Simply:

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

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

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

Use bootstrap .collapse instead of .hidden

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

16
votes

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.

14
votes

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();
5
votes

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.

5
votes

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.

3
votes

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();
});
2
votes

I like to use the toggleClass:

var switch = true; //it can be an JSON value ...
$("#my-div").toggleClass('hide', switch);
2
votes
$(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.

2
votes

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...
2
votes

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:

/**
 * The problem: https://github.com/twbs/bootstrap/issues/9881
 * 
 * This script enhances jQuery's methods: show and hide dynamically.
 * If the element was hidden by bootstrap's css class 'hide', remove it first.
 * Do similar in overriding the method 'hide'.
 */
!function($) {
    "use strict";

    var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide};
    $.fn.extend({
        show: function() {
            this.each(function(index) {
                var $element = $(this);
                if ($element.hasClass('hide')) {
                    $element.removeClass('hide');
                }
            });
            return oldShowHide.show.call(this);
        },
        hide: function() {
            this.each(function(index) {
                var $element = $(this);
                if ($element.hasClass('show')) {
                    $element.removeClass('show');
                }
            });
            return oldShowHide.hide.call(this);
        }
    });
}(window.jQuery);

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

2
votes

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

2
votes

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.

2
votes

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. :-)

1
votes

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/

0
votes

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
0
votes

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;
    };
0
votes

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.

-1
votes

☀️ 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();
}
-2
votes

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" );
    });
});