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>
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
You can use the jQuery addClass and removeClass methods to make the divs visible and invisible, e.g.: $("#id1"). removeClass("hidden"); and $("#id3"). addClass("hidden"); .
The hidden attribute hides the <div> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <div> element is not visible, but it maintains its position on the page.
Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.
div
has an ID.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.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With