Grow your CSS skills. Land your dream job.

Last updated on:

Toggle (Show/Hide) Element

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

Inline usage:

<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

Reference URL

Comments

  1. Permalink to comment#

    What is this? … Looks like it was scratched off a bathroom wall somewhere…

    Where’s the function statement? And how about using var for declaring local variables?

  2. Permalink to comment#

    the only problem i have with it is what i have to click the link twice the first time to make it disappear.

    • Drew
      Permalink to comment#

      Why does this need 2 clicks? I’m new at javascript, and this is driving me crazy!

    • someone
      Permalink to comment#

      change
      <div id="foo">This is foo</div>
      to
      <div id="foo" style="display:none;">

  3. Permalink to comment#

    This function works better!

    function toggle_visibility(id) {
    var e = document.getElementById(id);
    e.style.display = ((e.style.display!='none') ? 'none' : 'block');
    }

  4. I feel that the usage of display:none should be avoided if that is possible. Some versions of Webkit based browsers consider display:none like the element no longer a part of the DOM.

    Instead you can have a CSS class like the following one:

    .hidden{
    position: absolute;
    left: -9999px;
    top: -9999px;
    visibility: hidden;
    }

    After using JavaScript code you can add or remove the class name if you wish to hide or show the element respectively.

    The advantage is the element will be present in the DOM all the time but in a non-visible manner if it is in hidden state.

    • homi
      Permalink to comment#

      Very useful code snippet. Has been very useful to me. Keep up the good work

    • Permalink to comment#

      @Jayaprakash – This is the most correct method outlined here.

      @Escrimador

      As an old code hand you should remember the 3 layers of separation principle?
      Use JS to toggle (interaction) a class and let CSS to do the visual work.

      Personally I like to keep overrides as simple as possible:

      .hide {
      position: absolute;
      left: -200em;
      }

      Note the use of ems which pushes the content further off-screen the more the font-size is increased by the user.
      Works most of the time but sometimes you may need:

      .hide {
      position: absolute;
      left: -200em;
      width:0;
      height:0;
      overflow:hidden;
      }

      But that’d be rare and it’s best to use the minimum version until it fails.

  5. Pu
    Permalink to comment#

    This is great, thanks for your Support!

  6. Escrimador
    Permalink to comment#

    So when did display:none get deprecated? Do you even know the difference between visibility:hidden and display:none Jayaprakash?

    Now I’ve been a css developer since pre css days back in 1995 now almost 11 years as a Sr. UI Engineer and to this day many so-called css folks can’t even answer the simple question.

    Please if you’re giving css assistance, please be correct! Now do you even know when to use position:absolute and how to make it move with the “parent” elements when the browser resizes? Geez Louise…lmfao!!!

    Pretty obvious you don’t know css coding. Matter of fact display:none still exists in css3 along with all the other new pseudo classes.

    • MacGuyver

      You were a css developer before css was introduced?
      I would bow to your superior knowledge, but I use the internet without using the internet.

    • Nick
      Permalink to comment#

      @Escrimador are you just rude by nature or do you have to try at it? @Jayaprakash was simply pointing out that sometimes you want to hide an element but don’t want it disapearing from the DOM as that means your javascript program loses sight of it to.

    • Speaker-to-Animals
      Permalink to comment#

      visibility:hidden leaves a space where the item was, whereas display:none closes the gap so you can’t tell there’s a missing element in the layout.

    • Bobby
      Permalink to comment#

      I don’t think it was necessary to sound quite so condescending in order to answer a simple question. After a decade in the industry, you should know better than to act that way.

      Your big “stumper” that no one knows is pretty damned simple. visibility:hidden leaves the item in place but renders it invisible. display:none completely removes it. Not really that complicated, I’m pretty sure more people know this then you give credit for.

      Your entire post gives absolutely no information, it just makes you look like you need to prove yourself to someone. If you are going to criticize someone’s help, why not try to actually be helpful?

      And if you need help with your third paragraph, I suggest you look up inheritance and nesting. The latter more than the former.

  7. Escrimador
    Permalink to comment#

    Okay Pu, let me tell you something that Jayaprakash didn’t tell you because he is not a qualified css person.

    The difference between visibility:hidden is that although it is not visible on the web page, it still takes up space. Meaning, it the hidden element is say 500px wide by 500px high and in the middle of the page between lets just say a header and footer element, there will “ALWAYS BE A 500X500 EMPTY SPACE THAT’S VISIBLE ON THE WEB PAGE WHEN VISIBILITY:HIDDEN IS USED.”

    With display:none, with say the same elements a header and footer with an element in between set to display:none, there will be no visible and “UNWANTED WHITE SPACE VIEWABLE ON THE WEB PAGE” unless/until a call to action is made via javascript/jQuery or css. The same effect you get with drop-down menus and accordions.

    Be careful with the answers you read on blogs. It really infuriates me that some people are so loose with their answers and obviously don’t know what in the world they are talking about.

    • MacGuyver

      Says the man who claims he was developing css before css was introduced.

    • Nick
      Permalink to comment#

      @Escrimador, the class called hidden that @Jayaprakash suggested positions the element as absolute meaning it is removed from the flow. The left: -9999px and top: -9999px then moves it way off page. So once again you are wrong.

      .hidden{
      position: absolute;
      left: -9999px;
      top: -9999px;
      visibility: hidden;
      }

    • CSS Corrections
      Permalink to comment#

      @Escrimador – HA HA HA at you claiming to have worked with CSS before CSS was even around. Additional HA HA HA for you being so up to par on your CSS that you didn’t even know that the negative set values for top and left remove the element from the page, thus removing any chance of seeing white-space (which was the basis of your argument). I guess you needed to practice more with your CSS huh? I would figure you would have spotted that with your 10+ years of experience.

      He was right about one thing, even though his post was from 2011. You should be leery of blog posts because you may encounter an idiot like him who is a self-proclaimed expert yet failed to realize that the negative insertion removed the element, which even THIS novice knew. HA!

  8. Doc Brody
    Permalink to comment#

    The reaction to Jayaprakash was way out of line folks.

    He never actually said that display none was deprecated. There is really no reason to attack him personally.

    He simply said that some browsers handle it differently…. “Some versions of Webkit based browsers consider display:none like the element no longer [is] a part of the DOM”

    If this is true, it might explain some odd behavior I’ve seen. I sure would like to know definitively.

  9. Permalink to comment#

    I am using this method for faq’s where each answer is hidden by default and only shown when a question is clicked. Is there any way to target a specific question with a url and anchor that when visiting the link, it will scroll do that question and that answer will expanded by default?

    Thanks!

  10. Ntechi
    Permalink to comment#

    Hey hi Chris, I used jquery many times for toggle, in one my clients site this time I used CSS3 for toggle using :target. It really worked so I wrote a tutorial on it, sharing it here :)

    http://webstutorial.com/html5-css3-toggle-slideup-slidedown/html-5

  11. Gruber
    Permalink to comment#

    @Dillon @Drew that double cliking issue got me some problems too, but i’ve found a solution thanks to this post.

    In few words, the first click fires the if part of the function and ask “is the element display property set to block?” and the function terminate “prematurely” (so to speak) since it checks correctly that query. The second click put the script on work, since it has already checked the if requirement with the first click.
    So you have to sort-of “cheat” the script asking logic:

    
    
        function toggle_visibility(id) {
           var e = document.getElementById(id);
           if(e.style.display == 'none')
              e.style.display = 'block';
           else
              e.style.display = 'none';
        }
    
    
    

    With this only 1 click is needed, since it asks “is the element display property set to none?”, the function check that is not correct, and pass directly to the else part setting the desired effect!
    Hope this is somehow understandable, english is not my first language ;)
    Cheers!

  12. oliverosm
    Permalink to comment#

    one question how can i implement that in various divs.
    And thaks for sharing.

  13. oliverosm
    Permalink to comment#

    thanks i already found out how.

  14. Max
    Permalink to comment#

    I was wondering weather ther is a way of hiding the Content in the Div and opening it by clicking the anchor,rather than haveing it opne at the beginning and needing to click it tio close. So basically the oposite of the current script. thanks in advance.

    • Red5

      Great post Chris! Max, I was able to attain the results you prescribed by simply adding a display:none declaration to the element I am applying the script to.

      You then have to be sure the script is written as it is in Chris’s original post, where the script’s initial click displays the block, as such:

      <script type="text/javascript">
      function toggle_visibility(id) {
      var e = document.getElementById(id);
      if(e.style.display == 'block')
      e.style.display = 'none';
      else
      e.style.display = 'block';
      }
      </script>
      
      

      This will ensure that the element is not displayed when the page is loaded and only requires a single click to toggle it on.

  15. Permalink to comment#

    in using the show or hide element, i put two elements in the same div. what i want to do is hide one when the other is showing. this is because when one element is shown and the other is also revealed, the later one is superimposed on the older one. i would like only the new one to show. how can i do this?

  16. Alex

    Hey, thanks for this!
    I have an issue where the div is indeed showing and hiding as desired, but where I’m being taken to the top of page each time I click on the toggle. This is true in both FF and chrome. Any ideas?
    Thanks!

    • Permalink to comment#

      Hey Alex,
      That’s probably because the anchor target in the example is “#”, which’ll jump you to the top of the page because the browser is looking for an ID with no name. A link with a target of “#header” would likewise jump you to the element with the “header” ID!
      Using a span with an onclick event should let you drop the target entirely:
      <span onclick="toggle_visibility('foo');">Click me</span>

  17. Peter Lisi
    Permalink to comment#

    Really cool all around useful bit of code but I’d like to remove or hide the “Read More …” button once it’s clicked and the initially hidden content is now displayed.

  18. Leo VAP
    Permalink to comment#

    Thanks a lot ! very useful !

  19. Permalink to comment#

    I changed the code to to what it is below and it works perfectly fine. But one thing I am not too sure about is how to get an image to show up for both states, i want to use Expand and Collapse and it is not working. I am not a JS developer, I know HTML and CSS very well but not JS so much, I can understand it but I cant write it per se. Any ideas?

  20. KW
    Permalink to comment#

    I am curious, can anyone explain how to code so that when a toggle is opened the display shows the top of the toggles content?

    Whenever I use toggles with lengthy text in them, I have the problem where upon opening them, the screen shows the information from the bottom of the toggle field and not the top.

    I’d love to change that. Thanks for any help.

  21. Andrew Austin
    Permalink to comment#

    I’m having an issue in IE 9 (of all things) when using this toggle. I’m using it to toggle a nav and IE 9 actually eats my list items when this script is in place. Anyone had a similar issue or solution? Here’s my markup:

        <div id="mobile-nav-header"><a href="#" onclick="toggle_visibility('mobile-menu');">Menu</div>
        <nav id="mobile-menu" role="navigation">
            <ul>
                <li><a href="#photos">Photos</a></li>
                <li><a href="#etc">Et Cetera</a></li>
            </ul>     
        </nav>
    
  22. Brandon
    Permalink to comment#

    I can’t seem to make these functions work if the webpage has BOTH 1) a display: block div that must be triggered to hide and 2) a display: none div that must be triggered to appear. Reversing the logic of the function will either require 2 clicks to show and 1 click to hide, or 2 clicks to hide and 1 click to show. How can this function be written properly to apply to both situations with only 1 click?

  23. abner calapiz
    Permalink to comment#

    Hello WordPress what is the problem of this site – http://theblackcheese.org/category/blog/

    why post are not visible and the category post are not visible all post are not visible please help me.

    Best Regards,
    Abner

  24. Peter Osborne
    Permalink to comment#

    This script is excellent! Thanks for sharing. The one issue I am having is a way to properly ‘hide’ other div’s that were revealed by other click events. I have two buttons that I want to use this script on, but I need to have the content revealed by one button closed when I click the other button.

    I am not sure if this is making any sense. I just don’t want two sets of information revealed at the same time. Thanks for all your help in advance!

  25. Hi, I have read that Search Engines like Google ignores Javascript. So if I use this code to place text inside the toggle will it be ignored or will Google crawl the text?

    A quick reply on this will be really helpful.

  26. rina
    Permalink to comment#

    thank you……

  27. SK
    Permalink to comment#

    Hi,
    I have text links that all use “onClick Show/Hide”, but I would like for another image to be present in that space ‘before’ clicking on the links.
    Also I would like the ‘current’ text link to be bold until the next link is clicked on.
    I think this is probably an easy solution for all of you. Can anyone help? Thanks in advance. :)

    What I have: http://thispixelstudios.com/working/scottsdaleranch/index_test.html

    Example of what I want (vertical 4 link section): http://www.drsrtc.com/

  28. Permalink to comment#

    Thanks guys, somehow I managed to end up on CSS Tricks again after hopelessly reading about how to implement such a simple snippet on at least 5 different discussion boards around the web.

    I particularly want to point out other googlers to Steph’s < span > usage to avoid sending the user to the top of the page.

    Thanks again!

  29. This script works really well, thanks.

    But is there any way to add a little animation to it so it’s a little more smooth?

  30. aris

    Great, clear, brief!

  31. Permalink to comment#

    Any suggestions for adding transitions/animations to this?

    CSS transitions don’t work with the display property as far as I know.

    • Louis
      Permalink to comment#

      function toggle_visibility(id) {
      var e = document.getElementById(id);
      if(e.style.display == ‘block’) {
      //Set opacity to zero, with a CSS transition-duration of 0.3s
      e.style.opacity = ‘0’;
      //Set timeout of 300 ms (or the transition-duration of your CSS) to remove the element from the flow
      setTimeout(function(){
      e.style.display = ‘none';
      }, 300)
      } else {
      //Immediately put the element back into the flow
      e.style.display = ‘block';
      //Now set the element’s opacity to 1, which will be done nicely with CSS-transitions
      e.style.opacity = ‘1’;
      }
      }

      And you’re done ;)

  32. Don in Michigan
    Permalink to comment#

    HAHAHA – You guys are shitting me right? Please, continue as this is very entertaining. You guys are arguing over some snippets of code. You are all worse than a bunch of 14 year old girls arguing over Justin Bieber music lol…

  33. Bowman Kelley
    Permalink to comment#

    Great script and it doesn’t clash with the jQuery that was already being used on my page! Thanks

  34. Permalink to comment#

    I used this one for small project. But imo add/remove class is far better.

    function toggle(id) {
          el = document.getElementById(id);
          el.style.display = (el.style.display == '') ? 'none' : ''
        }
  35. Sergiu C
    Permalink to comment#

    Instead of using visibility:hidden, use display:none; so this by default hide you’r element, and create such animation that can slideToggle or just show and hide by making click event..

  36. Ermira
    Permalink to comment#

    Hi! I have implemented this function but the problem is that when the hidden element appears ,the rest of the page does not move down. So the element appears over the rest of the page. Is there any way to avoid this? Thank you!

  37. Permalink to comment#

    Hi, thanks for the handy code, it didn’t quite work for me in Chrome though- I had the 2 click problem. The reason is that starting with my div style set to display:none meant that e.style.display was an empty string ”, and not ‘none’. So the way to avoid the 2 clicks problem is to test that the string is NOT equal to ‘block’, which treats both ‘none’ and ” in the same way:

    function toggle_visibility(id) {
        var e = document.getElementById(id);
        e.style.display = ((e.style.display != 'block') ? 'block' : 'none');
    }
    
  38. Permalink to comment#

    Hi,
    Thanks alot all for sharing great stuff.
    I did everything you people showed which works great.
    I have a question.
    What if I want to link the hidden divs from another page so that when I click on that link it will open the specific div and keep the rest closed.
    Thanks alot.

  39. Permalink to comment#

    It can be done even simpler with JavaScript. CSS3 provides such feature, you can use the checkbox trick, here is example, it’s also simple as you JS: creating a toggle box to collapse or expand content using only CSS3

  40. Cat
    Permalink to comment#

    The function is great but how to use it in a table? <div> does not work well in table. What I have is a bunch of links in the table cells, and all of them are in class “page”:

    <table> <a href="visible1.html" rel="nofollow">visible page 1</a> <a href="visible2.html" rel="nofollow">visible page 2</a> <a href="test1.html" rel="nofollow">test1</a> <a href="test2.html" rel="nofollow">test2</a> <a href="test2.html" rel="nofollow">test3</a>

    How to code the javascript function to show/hide the links? Thanks!

  41. ftoweren
    Permalink to comment#

    some modifed >
    javascript:
    <script type="text/javascript">
    <!--
    function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'none'){
    e.style.display = 'block';
    }else{
    e.style.display = 'none';
    }
    }
    //-->
    </script>

    html:
    <input type="button" value="show" onclick="toggle_visibility('test');">
    <div style="display:none;" id="test">div contents</div>

  42. Dave

    nice, but you could animate it:

    function toggle_visibility(id) {
       var e = document.getElementById(id);
           if(e.style.height == '150px'){e.style.height = '0';}
       else{e.style.height = '150px';}
    }
    

    and add some style

    #mobileMenu{
    list-style: none;
    width: 100%;
    -webkit-transition:all 1s ease-in-out;
    height:0;
    overflow:hidden;
    }
    

    to a menu :)

    `<a href="#" rel="nofollow"></a>
    
    etc`
    
  43. tom
    Permalink to comment#

    Hello, how can I use this show hide to few elements? I want to have 3 ‘foo’ with the same id, no matter which one I click, I show/hide all of them. How can I edit this code?

    • Dixon
      Permalink to comment#

      Tom, to be knowledge, it doesn’t works that way to have multiple items with same id. My solutions would be doing something like

      JS function to accept a var of string with separator character like comma “,”

      function toggleMultiple(s) {
      var parts = s.split(“,”);
      for (var i=0; i < parts.length; i++) {
      var obj = document.getElementById(parts[i]);
      if (obj.style.display=='none')
      {
      obj.style.display='block';
      }
      else
      { obj.style.display='none'; }
      }}

      in element onClick="toggleMultiple('foo1,foo2,foo3');"

      Hope it helps.

  44. Mak
    Permalink to comment#

    Hi

    how would you use this that if you have multiple Div’s the one you click shows on screen and other Divs hide?

    • Dixon
      Permalink to comment#

      Mak,

      not very clear of your question, perhaps you may refer to code I suggested on tom. Could that be something you wish to do?

  45. Punit

    it’s working but how to hide click button and how to change the button of click time

  46. Erik Gloor

    Holy crap this little nugget totally helped me out of a jam. THANKS CHRIS!!!

  47. johnnyp
    Permalink to comment#

    you’re a genius!

  48. Didn’t work when I tried it in jsfiddle. Weird…

  49. Moh
    Permalink to comment#

    Hello
    Please how can i hide a DIV when the user clicks outside of it
    Thanks

  50. Marcus
    Permalink to comment#

    In what way do i change the code if i want the div to start hidden and then shown on click? :)

    Thanks

  51. Noxx
    Permalink to comment#

    Thank you! I’m extremely new to web development and know NOTHING about Javascript. If I look at it long enough I can figure out what it does, so this little chunk of code was perfect for what I wanted to do :)

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".