Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 716
Ouda Avatar asked May 26 '14 15:05

Ouda


People also ask

How do I hide a div and then show on click?

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 .

How do I initially hide a div?

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

How do I completely hide a div?

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.


1 Answers

Here I propose a way to do this exclusively using the Bootstrap framework built-in functionality.

  1. You need to make sure the target div has an ID.
  2. 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.
  3. Then, on your hyperlink (also works for buttons), add an href attribute that points to your target div.
  4. 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> 
like image 108
CowWarrior Avatar answered Oct 20 '22 12:10

CowWarrior