How to hide element using Twitter Bootstrap and show it using jQuery?
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;
}
Simply:
$(function(){
$("#my-div").removeClass('hide');
});
Or if you somehow want the class to still be there:
$(function(){
$("#my-div").css('display', 'block !important');
});
Use bootstrap .collapse instead of .hidden
Later in JQuery you can use .show() or .hide() to manipulate it
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();