How to hide, show, or toggle your div with jQuery


Hiding and showing content is MUCH easier with the magic of jQuery. Here is a simple demo of the jQuery .toggle() function.

Demo

Toggle Button

The content in this div will hide and show (toggle) when the toggle is pressed.

Here is the JavaScript needed to run this demo:

1
2
3
4
5
6
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function toggleDiv(divId) {
   $("#"+divId).toggle();
}
</script>


Line 1 simply loads the minimized jQuery v1.4.4 library. Once that is done, the rest is cake =) Line 3 defines the toggleDiv JavaScript function which takes one parameter: the id of the div to be toggled. Line 4 is where all the action takes place. The $("#"+divId) part is the powerful jQuery selector which selects the div that was passed to the function. I cannot say how easy jQuery makes it to select elements whether it is by id, class, or even by element types. Once our div is selected, we simply append jQuery’s toggle() function which automatically detects whether or not the content hidden and toggles it. On the HTML code level, the function toggles the display attribute between none and block.

Here is the raw HTML code for the demo:

1
2
3
4
<a href="javascript:toggleDiv('myContent');" style="background-color: #ccc; padding: 5px 10px;">Toggle Button</a>
<div id="myContent" style="background-color: #aaa; padding: 5px 10px;">
The content in this div will hide and show (toggle) when the toggle is pressed. 
</div>

The a tag is styled to look like a button and the onclick event uses our toggleDiv which passes the ‘myContent’ div ID as the argument. The rest of the HTML basically codes for our ‘myContent’ div whose content will be toggled by a click of the a tag.

That is it! There is no more need to reinvent the wheel my friends.


Here is a new demo in response to a request where only one div is displayed at any one time.

Demo
Div #1

Here is the HTML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table>
   <tr>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader1" href="javascript:showonlyone('newboxes1');" >show this one only</a>
         </div>
         <div class="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader2" href="javascript:showonlyone('newboxes2');" >show this one only</a>
         </div>
         <div class="newboxes" id="newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #2</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
            <a id="myHeader3" href="javascript:showonlyone('newboxes3');" >show this one only</a>
         </div>
         <div class="newboxes" id="newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #3</div>
      </td>
   </tr>
</table>

The HTML code contains 3 divs to start off with: 2 hidden and 1 displayed. Each link will launch the showonlyone JavaScript function and pass over the corresponding div ID.

1
2
3
4
5
6
7
8
9
10
function showonlyone(thechosenone) {
     $('.newboxes').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).show(200);
          }
          else {
               $(this).hide(600);
          }
     });
}

Line 2 contains some very cool uses of jQuery. Here we are looping through all divs with the class = "newboxes" which represents all 3 divs.

Line 3 checks to see if the div id in the current loop is equal to thechosenone which is the argument that was passed to the function.

If the id matches up, we use the .show() jQuery function to display the div. The argument 200 used in the .show() function will animate the display for a duration of 200 milliseconds. How cool is that =) If you leave it blank, the div will appear suddenly.

If the id does not match up, we simply use the .hide() jQuery function to hide the div. The argument 600 used in the .hide() function will animate the div so that it looks like it is sliding away. I used a higher number here so that you can see the difference in speed of the animations. Again, you can simply leave it blank if you want to make the div suddenly disappear.

That’s it!

If you would like all the divs to be hidden from the get go, simply use CSS to hide them all like so:

.newboxes {
    display: none;
}

Here is another quick example using the jQuery .slideDown() and .slideUp() functions.

Demo
Div #1

Everything is the same here except we are calling the .slideDown() and .slideUp() functions instead of the .show() and .hide() functions respectively. Even the animation duration is kept the same if you pass an argument to the function calls.

Here is the JavaScript code:

1
2
3
4
5
6
7
8
9
10
function slideonlyone(thechosenone) {
     $('.newboxes2').each(function(index) {
          if ($(this).attr("id") == thechosenone) {
               $(this).slideDown(200);
          }
          else {
               $(this).slideUp(600);
          }
     });
}

Not much explanation needed here. Same idea, different functions used.

Here is the HTML code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table>
   <tr>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader1" href="javascript:slideonlyone('newboxes1');" >slide this one only</a>
         </div>
         <div class="newboxes2" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px;">Div #1</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader2" href="javascript:slideonlyone('newboxes2');" >slide this one only</a>
         </div>
         <div class="newboxes2" id="newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #2</div>
      </td>
      <td>
         <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px;">
            <a id="myHeader3" href="javascript:slideonlyone('newboxes3');" >slide this one only</a>
         </div>
         <div class="newboxes2" id="newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px;">Div #3</div>
      </td>
   </tr>
</table>

Same thing here except we are calling the new slideonlyone() function that we just defined.

If you want all your div content to be hidden from the get go, simple use CSS to hide them like so:

.newboxes {
    display: none;
}

Here is a demo for changing text in the link according to the display status of the div:

Demo – Toggle link text and toggling div

Expanded text mode ▼

Div content that will be shown or hidden.

Here is the HTML code:

1
2
3
4
5
6
<a id="aTag" href="javascript:toggleAndChangeText();">
   Expanded text mode &#9660;
</a>
<div id="divToToggle">
   Content that will be shown or hidden.<strong>
</div>

Here we have an a tag that has the text that we want to toggle as well as the div content. Whenever the link text is clicked, it fires off the toggleAndChangeText() JavaScript function.

Here is the JavaScript code for the toggleAndChangeText() function:

1
2
3
4
5
6
7
8
9
function toggleAndChangeText() {
     $('#divToToggle').toggle();
     if ($('#divToToggle').css('display') == 'none') {
          $('#aTag').html('Collapsed text mode &#9658');
     }
     else {
          $('#aTag').html('Expanded text mode &#9660');
     }
}

Whenever the toggleAndChangeText() is fired off, it will first toggle the div with our nice jQuery toggle() function in line 2. Then it will test if the div content is hidden (or if the display attribute is set to none) in line 3. If so, it will change the link to “Collapsed text mode ►″. Otherwise, the link text will be changed to “Expanded text mode ▼″ in line 7.

To reverse the effect and start with the content hidden, all we have to do is the following:

1
2
3
4
5
6
<a id="aTag" href="javascript:toggleAndChangeText();">
   Collapsed text mode &#9658
</a>
<div id="divToToggle" style="display: none;">
   Content that will be shown or hidden.<strong>
</div>

The inline CSS is the key to making this work. We start with the content hidden which our JavaScript will detect so it will toggle to make the content visible once the link is clicked.


Next up is a pretty cool demo where we use the .animate() jQuery function to help toggle just about any element. In this case, we’ll use an image of yours truly :)

Demo
Click here to toggle me in and out =)

It's me....ah!!!

Here is the HTML code:

<div id="clickme" style="background-color: #333333; color: #FFFFFF; padding: 10px; width: 200px; cursor:pointer;">
  Click here to toggle me in and out =)
</div>
<img id="me" src="http://www.randomsnippets.com/wp-content/uploads/2011/04/2.png" alt="It&#039;s me....ah!!!" title="Allen Liu" width="100" height="77" class="alignnone size-full wp-image-552" style="border: none;" />

I have to apologize for all the inline CSS. This is the easiest way for me to get these demos across without having to separate the styling (which is usually best practice). I am trying to do good here so I hope the HTML Gods will spare me this one time.

Anyway, the HTML is quite simple. It is just a div with some text inside and a silly image. Notice there is no JavaScript event attached to our div just yet. This is where our jQuery code comes in and saves the day!

1
2
3
4
5
6
7
8
$(document).ready(function() {
     $('#clickme').click(function() {
          $('#me').animate({
               height: 'toggle'
               }, 2000
          );
     });
});

In line 1, we tell jQuery to wait until the DOM (Document Object Model) is fully loaded or when our page is fully rendered. We do this because we want to add functionality to our “click me” div. If the “click me” div has not yet loaded and this JavaScript executes, there is no element to work on. Game over.

Instead, we tell jQuery to wait until our “click me” div is in place, and then add a click event to it (line 2).

Lines 3-6 defines our click event by animating the $('#me') element which in this case is the image. If you are not used to jQuery syntax, $('#me') uses jQuery’s all-powerful selector to help us select the element with id = me.

Once we have our element selected, we apply the animate function to add animation to this element’s CSS properties. We first begin with line 4 which toggles the height of the element and preserves the height:width ratio which gives it a shrinking effect. We use toggle here so that you can keep pressing the button to toggle in and out. You can of course use show or hide just like in the previous demos.

Line 5 just indicates how long the duration of our animation will last in milliseconds. In this demo, it is 2000 milliseconds which translates to 2 seconds (I was in AP math in high school).


Here is a demo that toggles multiples elements by the class attribute.

Demo


1
2
3
4
5
6

Here is the HTML code along with the CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<style type="text/css">
.evenNumber, .oddNumber {
     width: 100px;
     height: 100px;
     margin: 10px;
     padding: 10px;
     float: left;     
     background-color: #333333;
     color: #FFFFFF;
}
</style>
<button onclick="toggleByClass('oddNumber');">Toggle odd numbers only</button>
<button onclick="toggleByClass('evenNumber');">Toggle even numbers only</button>
<div class="oddNumber">1</div>
<div class="evenNumber">2</div>
<div class="oddNumber">3</div>
<div class="evenNumber">4</div>
<div class="oddNumber">5</div>
<div class="evenNumber">6</div>

Lines 1-11 covers the styling of the divs so they are presentable.

Lines 12-13 codes for 2 buttons that toggles the odd number divs and even number divs respectively by calling the toggleByClass function and passing the respective class names.

Here is the JavaScript code:

1
2
3
function toggleByClass(className) {
     $("."+className).toggle();
}

Simple and sweet but a lot is going on here. Let’s dissect line 2 and cover each component separately.

$("."+className) uses the jQuery class selector with the className variable representing the class of the element(s) you want to select. In our demo, we use the oddNumber and evenNumber class names to select for their respective divs.

Once the divs are selected, we tack on the .toggle() jQuery function to hide and show the elements.

Here is a tutorial that shows how to hide or show content based on links on different pages.

That is it for yet another demo =)

If there any other demos/tutorials that you would like to see on this subject, please feel free to comment below and I will try my best to implement it.

Note: If you have an issue with your code, please give me a URL to work with. It’s extremely difficult for me to help if I cannot actually see the code.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!