261

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?

1
  • 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. Oct 29, 2018 at 1:30

22 Answers 22

446

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;
}
10
  • 4
    Thank you so much I was wondering stackoverflow for something like this for long time for simple answer. Thank you
    – Dil.
    Jul 27, 2015 at 10:53
  • Anyone has an idea what are the methods: show() and hide() for then?
    – checklist
    Apr 26, 2016 at 5:11
  • 9
    Then you can't animate it (eg. fadeIn()). Therefore use the class collapse instead of hidden. And then of course there is no need for using removeClass, addClass, etc. Aug 22, 2016 at 15:28
  • 2
    For Bootstrap 4 you have to use .hidden-xs-up. v4-alpha.getbootstrap.com/layout/responsive-utilities/… There is also hidden HTML5 attribute. v4-alpha.getbootstrap.com/content/reboot/…
    – Chloe
    Jun 12, 2017 at 1:05
  • 1
    @Kangur jQuery .hide() isn't bootstrap's .hide class. The jQuery method works fine, but it's not the bootstrap way. Bootstrap libraries depend on the inclusion of the .hidden class on the element to determine it's not there. jQuery doesn't add that -- unless you hack it like here: stackoverflow.com/a/27439371/124486, in which case you could break other jQuery specific things. Dec 29, 2017 at 18:16
66

Simply:

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

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

$(function(){
  $("#my-div").css('display', 'block !important');
});
2
  • 1
    Here's a jQuery plugin that allows you to use .show() and .hide() even with the bootstrap 'hidden' and 'hide' classes. gist.github.com/zimkies/8360181
    – zimkies
    Jan 10, 2014 at 18:49
  • 9
    According to Bootstrap documentation, .hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1. Use .hidden or .sr-only instead.
    – bjtilley
    Jan 20, 2014 at 15:17
26

Use Bootstrap's .collapse instead of .hidden.

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

1
  • THIS is the correct answer, the accepted one has !important and while it's possible to show it by toggleClass, jquery .show and .slide won't work with that one, but will work this one. Thanks Aug 31, 2022 at 19:47
18

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.

4
  • 1
    .hide is deprecated as of v3.0.1 Feb 2, 2015 at 23:44
  • 2
    Ok, use .hidden as of v3.0.1 Feb 4, 2015 at 0:08
  • In this case, there might be flickers of content that is shown for microseconds before hidden with JS. Sep 15, 2019 at 15:16
  • Calling .hide() first applies display:none; to the style tag. This happens prior to removing the hide class. If you have it in that order, it shouldn't flicker. Sep 16, 2019 at 16:37
14

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();
3
  • It circumvents the problem posed by using bootstrap's classes. Why downvote this short and simple solution?
    – dbrin
    Feb 3, 2015 at 0:36
  • Because this short and simple solution doesn't answer the question which specifically calls for the use of bootstrap3's classes. Not to mention, while simple, .hidden in Bootstrap is defined as .hidden { display: none !important; visibility: hidden !important; } Feb 3, 2015 at 8:07
  • 2
    and that is exactly the problem, JQuery hide and show methods do not work well with this css.
    – dbrin
    Feb 3, 2015 at 17:25
5

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.

1
  • So elegant and simple -- you just overcame a common Bootstrap deficiency. I would use hidden class and then try to do show() in jQuery, and nothing would happen. Your solution fixes this so easily, and I didn't think of it.
    – Volomike
    Mar 1, 2015 at 0:41
5

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.

4

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

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

I like to use the toggleClass:

var switch = true; //it can be an JSON value ...
$("#my-div").toggleClass('hide', switch);
1
  • This would be great, but the switch is entirely not needed. Feb 3, 2015 at 8:10
2

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...
1
  • 3.1 doesn't support .hide, it has .hidden. Feb 2, 2015 at 23:46
2

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
  • 1
    Is it necessary or optimal to check if the class exists before you call .removeClass() or .addClass()? Feb 3, 2015 at 17:31
  • Also, doesn't .removeClass() already work over the set? Couldn't you simply call $(this).removeClass('show') Feb 3, 2015 at 17:32
2

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

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

2
$(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

In Bootstrap 4 you can use the d-none class to hide an element completely.

Display property

1

Hide and hidden are both deprecated and later removed, and they 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 the visibility and display utilities:

Visibility

Display property

0

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

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

    /*
     * .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

There is a solution without jQuery

You can use the CSS Pseudo class :Active to hide the element when clicked. This pseudo class is mainly used on anchor tags and buttons.

So for instance.

a:active { display: none; }         /* Active links */
<a href="#">This will disappear when it is clicked.</a>

Example with button

#btn-01:active ~ p {
            display: none;
         }
<button id="btn-01"> click me</button>
<p id="text">Some Example Text</p>

-1

I solved my issue by editing the Bootstrap CSS file. See their documentation:

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

-2

Bootstrap provides classes for toggling content. See bootstrap/less/utilities.less.

I'm completely new to jQuery, and after reading their documentation I came to another solution to combine 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 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 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 Bootstrap, which is optimized for [assistive technology][3] as well (screen readers). So, if we want to show the hidden div, we need to get rid of the .hidden class of 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 use .toggleClass 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 Bootstrap 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" );
    });
});
3
  • @EvanCarroll, why is it complex? I've been reading your answer as well and I see you suggest to use toggleClass which I also do, so I don't understand your comment. Feb 4, 2015 at 8:35
  • The link for the last reference, near "class back again" is missing (also in the first revision). Mar 3 at 23:30
  • OK, the OP has left the building: "Last seen more than 6 years ago" Mar 3 at 23:31

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.