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. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  2. <script type="text/javascript">
  3. function toggleDiv(divId) {
  4.    $("#"+divId).toggle();
  5. }
  6. </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. <a href="javascript:toggleDiv('myContent');" style="background-color: #ccc; padding: 5px 10px;">Toggle Button</a>
  2. <div id="myContent" style="background-color: #aaa; padding: 5px 10px;">
  3.     The content in this div will hide and show (toggle) when the toggle is pressed. 
  4. </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. <table>
  2.    <tr>
  3.       <td>
  4.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  5.             <a id="myHeader1" href="javascript:showonlyone('newboxes1');" >show this one only</a>
  6.          </div>
  7.          <div class="newboxes" id="newboxes1" style="border: 1px solid black; background-color: #CCCCCC; display: block;padding: 5px; width: 150px;">Div #1</div>
  8.       </td>
  9.       <td>
  10.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  11.             <a id="myHeader2" href="javascript:showonlyone('newboxes2');" >show this one only</a>
  12.          </div>
  13.          <div class="newboxes" id="newboxes2" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #2</div>
  14.       </td>
  15.       <td>
  16.          <div style="border: 1px solid blue; background-color: #99CCFF; padding: 5px; width: 150px;">
  17.             <a id="myHeader3" href="javascript:showonlyone('newboxes3');" >show this one only</a>
  18.          </div>
  19.          <div class="newboxes" id="newboxes3" style="border: 1px solid black; background-color: #CCCCCC; display: none;padding: 5px; width: 150px;">Div #3</div>
  20.       </td>
  21.    </tr>
  22. </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. function showonlyone(thechosenone) {
  2.      $('.newboxes').each(function(index) {
  3.           if ($(this).attr("id") == thechosenone) {
  4.                $(this).show(200);
  5.           }
  6.           else {
  7.                $(this).hide(600);
  8.           }
  9.      });
  10. }

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:

  1. .newboxes {
  2.     display: none;
  3. }

Update: This is a cleaner version of the showonlyone script that is more elegant and has done away with using table tags. The button also toggles the div instead of just being able to show the div.

This is a version of the updated script that slides the divs:


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

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

Here is the HTML code:

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

  1. .newboxes {
  2.     display: none;
  3. }

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. <a id="aTag" href="javascript:toggleAndChangeText();">
  2.    Expanded text mode &#9660;
  3. </a>
  4. <div id="divToToggle">
  5.    Content that will be shown or hidden.<strong>
  6. </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. function toggleAndChangeText() {
  2.      $('#divToToggle').toggle();
  3.      if ($('#divToToggle').css('display') == 'none') {
  4.           $('#aTag').html('Collapsed text mode &#9658');
  5.      }
  6.      else {
  7.           $('#aTag').html('Expanded text mode &#9660');
  8.      }
  9. }

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 &#9658”. Otherwise, the link text will be changed to “Expanded text mode &#9660” in line 7.

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

  1. <a id="aTag" href="javascript:toggleAndChangeText();">
  2.    Collapsed text mode &#9658
  3. </a>
  4. <div id="divToToggle" style="display: none;">
  5.    Content that will be shown or hidden.<strong>
  6. </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. $(document).ready(function() {
  2.      $('#clickme').click(function() {
  3.           $('#me').animate({
  4.                height: 'toggle'
  5.                }, 2000
  6.           );
  7.      });
  8. });

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

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 =)

Here is a similar post that provides a non-Javascript solution to hide or show content.

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! OR…you can sign up for a free Dropbox account using my referral link =) If you are not aware of what Dropbox is, it is the most awesomest online backup application there and so much more…all for free.





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

377 thoughts on “How to hide, show, or toggle your div with jQuery”

  1. Love the code. Simple. I do have an issue with how the site im using uses this. Currently, the data I want users to be able to hide/show is shown by default. How could I make it visible by default?
    Example the league page for our madden league. http://Www.daddyleagues.com/madscrubs
    Notice the NFC Standings and AFC Standings are able to be hidden/shown but are shown by default. How can I change it that they are hidden when you visit the page first?

    1. Hi Jerry,

      Add the following CSS to your “panel-body” class:

      .panel-body {
          display: none;
      }

      That should do it!

      Allen

  2. You are very generous for sharing all of this. I will definitely “buy you a beer” when I get paid for my current struggle.

    Having said that, I have successfully applied your pure JavaScript showonlyone (version 2) and I have successfully applied your JQuery slideonlyone… I need the “close-self” feature of the first to fit the later.

    I need the JQuery slideonlyone to display:none on a second click (without having to click on another activation point).

    If you could point me in the right direction that would be great. I would post a fiddle or a url – but you’d just be looking at your own code and the website is in the sandbox.

    Any help is greatly appreciated.

      1. Thank you much for your prompt reply. This is similar to the straight JS alternative to the JQuery I was working with. I was wondering if there was a way to add easing? That’s what attracted me to the JQuery solution.

          1. THANKS – this is exactly what I was looking for. You are awesome. There are not enough good, helpful people like you out there. I won’t forget this.

  3. What would a function look like that would turn off the background image on a page when you select any menu item

    1. Hi Tom,

      If you can create a jsFiddle recreating the type of menu you have I can probably give you a more precise example but this is how you would turn off the background image with jQuery:

      $('#theElementId').css('background-image', 'none');

      I hope it helps.

      Allen

  4. Hi Allen,

    I really don’t know much about coding but I am trying to get these elements into Mailchimp for an email campaign I have to send out daily (ideally I would like to be able to list the article title and then have the article text drop down once someone clicks on it, which most of these options seem like I could do that with).

    However, putting these codes into Mailchimp do not result in a click-able email. Please advise and I apologize if it’s a really simple answer that I missed!

    1. Hi Grace,

      I’m not 100% sure but I don’t think that is possible. I know for sure that you won’t be able to embed Javascript in emails for security reasons. There may be a CSS hack that may allow you to do this but you may need to test it in an actual email. Here is a simple CSS example of showing and hiding content based on the hover pseudo-class:

      https://jsfiddle.net/axl163/tz0yjacd/

      Hope it helps.

      Allen

        1. Hi Grace,

          I just thought of another possible CSS solution that uses the focus pseudo-class:

          https://jsfiddle.net/axl163/tz0yjacd/

          The “button” is actually a textbox. When a user “clicks” or focuses in on the input, the focus pseudo-class will show the content. This behavior is more in line with what you initially requested.

          Allen

  5. Hi Allen,
    Great Scripts!

    I have a question about toggles multiples elements by the class attribute. How can I do that only one div(in this case only one class) is displayed at any one time (in your toggles multiples elements script)?

    Regards,
    Matt

    1. Hi Matt,

      Take a look at the demo where the buttons say “Toggle odd numbers only” and “Toggle even numbers only”. That is driven by the class attribute.

      Allen

  6. Hello Allen,
    First of all thank you so much for these snippets :) they have been most useful for me, I am new to Jquery and I really like your first example where you have:

    function toggleDiv(divId) {
    $(“#”+divId).toggle();
    }

    I just have a simple question, is there a way of adding a class when a div has been clicked? Like .addClass of “active”? I tried to add it in different ways but got errors :(

    Thank you once again for the super scripts and keep up the good work!! :)
    Kind regards,
    Tony

  7. You wanted to give you a big Thank You! You tips on hiding and showing div(s) helped me ace my Udacity final test on Intro to Programing. I am still on my journey to learn and hopefully become a Jr. front end programer soon. I will keep this website on my favorite list and I am forever grateful for the resource you have given me.

  8. After hours of testing solutions, debugging and really just struggling, I found this article.

    I can’t say it loud enough. THANK YOU!

    This turned my over-caffeinated frown upside down. :)

  9. Hey, Allen. I’m running into an issue whereby the script works only in certain browsers, IE and Chrome. I don’t have very much scripting knowledge, so my ability to troubleshoot is quite limited. Any idea why the script wouldn’t be working in Safari mobile or Firefox? (When I load your page here in both of those browsers all of examples work perfectly!!!)

    Here’s the URL: http://web.crdn.com/crdncom-ag6vm/pages/104f4b412187e511abb7005056b849c0.html

    Appreciate any guidance you can offer!

    1. Welp! When I tested the page yesterday, it wasn’t working across all browsers. Today, after having changed nothing with the script or code, the page seems to be functioning properly in both Safari Mobile and Firefox, as well as others. Can’t explain that one, but it’s doesn’t look like I need any assistance troubleshooting at this point. Ha!

  10. Thanks for posting this, it’s almost exactly what I’m looking for. I’d like to use the “show one at a time” option but using a hover instead of toggle. Is that possible?

      1. Thanks for the quick comeback Allen, but I’m having problems. The code in your link works fine but when I put in an html page it doesn’t work. Here’s my code.

        Demo

        $(‘.trigger’).on(‘mouseover, mouseenter’, function() {
        $(this).next(‘.door’).slideDown();
        });

        $(‘.trigger’).on(‘mouseleave’, function() {
        $(this).next(‘.door’).slideUp();
        });

        .block {
        width: 120px;
        display: inline-block;
        vertical-align: top;
        }
        .trigger {
        padding: 12px;
        background-color: #333;
        color: #ffffff;
        }
        .door {
        padding: 12px;
        display: none;
        background-color: #yellow;
        }

        open door 1

        behind door 1 is a foo

        open door 2

        behind door 2 is a bar

        open door 3

        behind door 3 is a “hello world”

        1. Unfortunately, this doesn’t help much. I’d probably need the url of the page so that I can see the actual layout of the code. My guess is that you did not include a jQuery library. Include the following code within your head tags:

          <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>

          Let me know if that works out for you. If not, please give me the url of the page and I should be able to better help you.

          Allen

            1. Ok. I think I see the issue. Your JavaScript needs to be executed after the document is loaded. Try wrapping your code in the $(document).ready() function.

              $(document).ready(function() {
                  $('.trigger').on('mouseover, mouseenter', function() {
                      $(this).next('.door').slideDown();
                  });
               
                  $('.trigger').on('mouseleave', function() {
                      $(this).next('.door').slideUp();
                  });
              });

              What this does is delay the execution of your JavaScript until the document is loaded. My guess is that your JavaScript is running but the html elements are not yet rendered so there is nothing to act upon.

              Let me know if this works.

              Allen

  11. hey, made use f your code for the first example of showing or hiding text… just a quick qn how do i do it so that the text is innitially hidden then when the link is pressed it shows up

  12. Hi Allen, these tuts are amazing.
    Can I request for one more piece of code?
    I have a total of 27 elements. Initially I want to show 9 of them, afterwards there will be a button to show the next 9 elements, and the button will disappear once the elements finish showing. Can you help me with that?
    Will definitely buy you a beer!

Leave a Reply

Your email address will not be published. Required fields are marked *