Hide div by default and show it on click with bootstrap
I want to show and hide a div
, but I want it to be hidden by default and to be able to show and hide it on click. Here is the code that I have made :
<a class="button" onclick="$('#target').toggle();">
<i class="fa fa-level-down"></i>
</a>
<div id="target">
Hello world...
</div>
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
- You need to make sure the target
div
has an ID. - Bootstrap has a
class
"collapse", this will hide your block by default. If you want your div to be collapsible AND be shown by default you need to add "in" class to the collapse. Otherwise the toggle behavior will not work properly. - Then, on your hyperlink (also works for buttons), add an href attribute that points to your target div.
- Finally, add the attribute
data-toggle="collapse"
to instruct Bootstrap to add an appropriate toggle script to this tag.
Here is a code sample than can be copy-pasted directly on a page that already includes Bootstrap framework (up to version 3.4.1):
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>
<button href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</button>
<div id="Foo" class="collapse">
This div (Foo) is hidden by default
</div>
<div id="Bar" class="collapse in">
This div (Bar) is shown by default and can toggle
</div>
Just add water style="display:none";
to the <div>
Fiddles I say: http://jsfiddle.net/krY56/13/
jQuery:
function toggler(divId) {
$("#" + divId).toggle();
}
Preferred to have a CSS Class .hidden
.hidden {
display:none;
}
Try this one:
<button class="button" onclick="$('#target').toggle();">
Show/Hide
</button>
<div id="target" style="display: none">
Hide show.....
</div>