Javascript Code to show a hidden element | Display and Visibility

    The Overview:

    Here’s a quick javascript trick to control display settings. See it in action here: jsToggle.
    All we do is set the display of an element to none, and then use a javascript function to toggle the display when a user clicks something else.

    The Steps:

    1. So pick an id and set it’s style=”display:none” (if this is in the css however, the javascript won’t override it, so just put it as an element attribute).

    2. Then attatch a javascript onclick event to a link or anything really, I used a link just because it’s something we are used to clicking on.

    3. Add this javascript function to the page. It searches the DOM for the element id (getElementById) and toggles the display state.

    Here’s the code:

    function toggleVisibility() {
      document.getElementById("toggleMe").style.display = "";
      if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
        document.getElementById("toggleMe").style.visibility = "visible";
      }
      else {
      document.getElementById("toggleMe").style.visibility = "hidden";
      }
    }
    function toggleDisplay() {
      document.getElementById("toggleMe").style.visibility = "visible";
      if(document.getElementById("toggleMe").style.display == "none" ) {
        document.getElementById("toggleMe").style.display = "";
      }
      else {
        document.getElementById("toggleMe").style.display = "none";
      }
    }
    <p><a href="#" onclick="toggleDisplay();">Click to toggle display.</a> | <a href="#" onclick="toggleVisibility();">Click to toggle visibility.</a></p>
    <div id="toggleMe" style="visibility: hidden;"> Something to Hide and show. Display collapses it's layout while visibility will keep it's layout.</div>

    The Example:

    To see it working: jsToggle display.
    jsToggle visibility.

    The Download:

    jsToggle.zip

    UPDATE:

    please view the newest post I’ve written about javascript being used to show and hide elements with the help of jQuery tutorial.

    This entry was posted in tutorial and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

    36 Comments

    1. n00bie
      Posted January 16, 2008 at 5:09 am | Permalink

      Hey, this is great and simple trick – and, it works! Thanks a bunch, I’ll make sure I use it!

      One question, though.. if you have multiple hidden objects, they can’t use the same id, right.. So this wouldn’t work in that case?

      How could i make it work with multiple hidden objects? By passing an argument when calling the function, and renaming each object with individual id’s… or?

      Sorry, i’m a noob, as my name states.

    2. n00bie
      Posted January 16, 2008 at 6:06 am | Permalink

      Ok, i solved it on my own. Man, do I feel like a genius now.. (I’m only just learning javascript and stuff).

      It took a little thinking, but in the end it was quite easy. I just had to change the toggleDisplay() function so, that every time it’s called, I pass it an argument, which it then uses with each getElementById function to define which element it needs to toggle.

      And of course, each element had to be named with unique id, like item1, item2, etc..
      and when calling them with onclick=”toggleDisplay(‘item#’)”, I just used that unique id, instead of #, of course. Works like a charm.

      Once again thanks for the original snippet! I love your blog. ^^

    3. Posted January 16, 2008 at 10:46 am | Permalink

      @ n00bie,

      Thanks for the kind words!

      You answered your question exactly as I would have. Kudos to you! Be sure to post a link to your work and I’ll be sure to check it out!

    4. Kes
      Posted February 13, 2008 at 11:31 am | Permalink

      just thought I’d say: thanks for the code! =)

    5. Sumant
      Posted April 29, 2008 at 7:23 pm | Permalink

      Awesome post buddy…..
      i had to go through a lot of stuff before i got to your post.,…..but it was worth it……
      a lot of people have posted on this topic but no one has taken in to consideration the one simple thing that you have….which is to define the style = “display : none”…..
      due to this missing part my code was breaking at “document.getElementbyID.Style”
      but your post solved that big mystery…thanks a lot again……keep rocking!!!

    6. Amandeep
      Posted May 12, 2008 at 3:18 pm | Permalink

      IS there a way to block space for the hidden elements , so that when the element is made visible the complete page elements are not realigned.

      I have a requirement where display of few columns of certain rows in a table have to be toggled.
      When the column values are hidden,I need there space to be blocked.

      IS there a way out?

    7. Posted May 13, 2008 at 12:28 pm | Permalink

      Amandeep,
      So you want to hide your column, but have it’s place left blank?
      I’d have to see your design to say which would be best, but there are a few ways you could do this:
      1. You could try having an empty column to be swapped out with the one you have content in when you hide/show the content.
      2. You could try changing the color to make the text invisible on the background but still hold it’s place.
      3. Maybe display=none isn’t the style property you’re looking for: try swapping out the ‘display: none;’ with ‘visibility: hidden;’ and ‘display=”"‘ with ‘visiblilty=”visible”‘ Display is a property that will change the layout of the page, while visibility leaves the layout the same and hides the content.
      Here’s the source code

            function toggleVisibility() {
            if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
            document.getElementById("toggleMe").style.visibility = "visible";
            }
            else {
            document.getElementById("toggleMe").style.visibility = "hidden";
            }
            }
            <p onclick="toggleVisibility();">Click to toggle.</p>
            <p id="toggleMe" style="visibility: hidden"> Something to Hide, but still affects layout.</p>
    8. Posted May 13, 2008 at 1:12 pm | Permalink

      I’ve updated the files to have toggleDisplay() and also toggleVisibility() functions. Let me know how it goes!

    9. Susan
      Posted May 28, 2008 at 11:27 pm | Permalink

      I have the same issue that nOObie had — I have multiple items I want to toggle the display on. I’ve changed the id so that they are each unique, but I don’t know how to write the ‘argument’ when the function is called to make them work properly. Right now clicking on any of the ‘toggle item’ links makes just the last item toggle. Can anyone give me help?

    10. Posted May 29, 2008 at 12:47 pm | Permalink

      @Susan-
      Yes, each element needs it’s own id, the above function is just for hiding/showing the specified id ‘toggleMe’ which is hard coded in the function. You can pass in an argument which would abstract the functionality of the function quite a bit: You pass in the specific element id you want to toggle.

      function toggleSpecific(elementid) {
        var node = document.getElementById(elementid);
        if(node.style.display == '') {
          node.style.display='none';
        }
        else {
          node.style.display = '';
        }
      }

      And here’s some html example for how to use it.

      <div onclick="toggleSpecific('hide1');">Click to Hide 1</div>
      <div onclick="toggleSpecific('hide2');">Click to Hide 2</div>
      <div onclick="toggleSpecific('hide1');toggleSpecific('hide2');">Click to Hide Both</div>
      <div>or using anchor tags: <a href="javascript:toggleSpecific('hide2');" title="Hide2">Click this link to hide 2</a></div>

      <div class="hide" id="hide1">Hide this one</div>
      <div class="hide" id="hide2">Hide this too</div>

      Here, I’ve uploaded another example page: jsToggleSpecific.html

      • Posted May 9, 2011 at 1:51 pm | Permalink

        Thank you so much! This has been so helpful to me! Out of all the many web pages I have visited, yours has been the most concise and most easy to understand!

    11. Posted June 26, 2008 at 4:16 am | Permalink

      Great post – clear and concise.
      Can you help me take it further? Is it possible to pass the onclick from flash? For example, I have a flash movie, which when clicked turns a page. But I’d also like this click to display a normal html menu. So I could use this post to do it (I think) but I’m not a flash guy though and I’m struggling to see the relationship between the actionscript and the javascript. Any pointers?

      Thanks

    12. Posted June 26, 2008 at 12:45 pm | Permalink

      @faolie- sure! It shouldn’t be hard.
      I’ve already detailed actionscript and javascript communication, it should be simple to combine these two techniques into one for your project…
      Check this post out: Actionscript Javascript Communication | ExternalInterface call and addCallback Tutorial

    13. Posted July 1, 2008 at 11:49 am | Permalink

      Hi, thanks. Quite simple really – here’s what I used if anyone wants to know:

      on (press) {

      import flash.external.*;
      ExternalInterface.call(“toggleVisibility”);
      }

    14. David
      Posted July 18, 2008 at 9:35 pm | Permalink

      Very useful script, which, unlike the one I had been using, works in Firefox.

      I have a question: How important is /title=”Hide1″/ in your script? I left it out, and its absence did not impair the running of the script at all.

    15. Posted July 19, 2008 at 5:07 pm | Permalink

      @ David – Thanks! I’m guessing you’re meaning title=”Hide2″ ?
      I don’t see any other place I use title… Title is just the text that appears when you hover over the link.
      The id has to be specific and that’s how the script knows what to change and the class is just used for styles.
      Hope that helps! =)

    16. David
      Posted July 20, 2008 at 3:13 am | Permalink

      Yes, that helped. In short, title=* performs the same function as the alt=* property after an IMG tag in HTML, and is likewise optional. Thanks.

    17. sk
      Posted May 3, 2009 at 2:50 pm | Permalink

      Evan,

      In regard to your script above for multiple toggles:

      I want the text “Show” (or [+]) to appear when the text is hidden, and the text “Hide” (or [-]) to appear when it is already expanded.

      How would you go about doing that?

      Thanks in advance.

      • Posted May 7, 2009 at 4:50 pm | Permalink

        This isn’t too hard, just takes a few more lines. Have your “Less [-]” link inside the div that will be hidden, and when it is hidden, then show a separate div that simply says “More [+]“. So rather than just showing/hiding one element on the page you just need to show one and simultaneously hide another.

    18. kassim
      Posted November 11, 2009 at 10:43 am | Permalink

      HI this is my code …here if i click my link it toggle’s the text …but it movin automatically to the top of the page ….help me out ….

    19. jojo
      Posted February 3, 2010 at 3:54 am | Permalink

      Hi this posting is awesome..

      But how can i make it this event onclick to onmouseover?
      I tried it but its not working well.

      Please help me…

    20. russ
      Posted June 14, 2010 at 3:34 pm | Permalink

      Lotsa info on your nice site, will like to peruse it later, but now…

      I’m trying to find a way to toggle a set of divs with buttons so when a button is clicked it both toggles the visibility of its associated div, AND hides any other div that may be showing at the time. (The divs are stacked translucent pngs over a background image so only one can show at any time.)

      I’ve found all sorts of variations on javascript toggling, but none yet that works like this (and I’m not smart enough to craft it from them). Would appreciate any help you might be able to give.

      thanks!
      russ

      • Posted June 14, 2010 at 4:43 pm | Permalink

        russ- it would be pretty simple, what you’d want to do is have two separate id’s addressed in the function, just show one and hide the other.

        function toggleDisplay() {
          if(document.getElementById("toggleMe1").style.display == "none" ) {
            document.getElementById("toggleMe1").style.display = "";
            document.getElementById("toggleMe2").style.display = "none";
          }
          else {
            document.getElementById("toggleMe1").style.display = "none";
            document.getElementById("toggleMe2").style.display = "";
          }
        }

        best,

        • russ
          Posted June 14, 2010 at 5:13 pm | Permalink

          thanks evan for your help, but this logical code seems like it would work for only one button and two divs. I will have several buttons, each for showing/hiding a related div. Can I give the toggleDisplay functions id’s (like div’s), then associate each id’ed function with a button? again, mucho gracias.

          • Posted June 14, 2010 at 5:30 pm | Permalink

            I’d set up the function to accept a parameter, then you can pass the specific div you want shown and have it hide the rest.

            function showMe(toShow){
            document.getElementById("toggleMe1").style.display = "none";
            document.getElementById("toggleMe2").style.display = "none";  document.getElementById("toggleMe3").style.display = "none";
            document.getElementById("toggleMe4").style.display = "none";

            document.getElementById(toShow).style.display = "";
            }

            and then from each button you would call the same function but pass in the specific id.

            <a href="#" onclick="showMe('toggleMe4');">Click to toggle display.</a>
    21. russ
      Posted June 14, 2010 at 5:31 pm | Permalink

      EUREKA! Figured it out (am I smart after all??)

      individually named functions attached to buttons, each setting one div to display and the others to hide.

      awesome, thanks so much!

    22. Nazeer
      Posted July 3, 2010 at 12:04 pm | Permalink

      Great Post.

      I’m running into a problem were I have SWFObject is placed into a DIV tag in the HTML Page. I have registered javaScript CallBack (ExternalInterface) function in this SWF file to do some action when a HTML button pressed/onClicked. This is very simple and up to this point works perfectly.

      But it’s failed in IE after applying style to that DIV tag.Basically I’m trying to invoke the registered action script function from java script. Again this works in Mozilla not in IE.

      Here is some of the style I used for the DIV tag the one contains the SWFObject.

      document.getElementById(“two”).style.visibility = ‘hidden’

      document.getElementById(“two”).style.filter=”alpha(opacity=80)”;

      Looks like the interface get unregistered by itself when the style applied to the container tag(DIV tag).

      Well I’m not a HTML expert, not sure this might be a bug /???..

      Any suggestion here?

    23. Shoaib
      Posted September 30, 2010 at 6:03 am | Permalink

      it worked for me in firefox but not in Internet Explorer 8
      please what do I do for that?
      I have just started to learn js stuff…

    24. Shoaib
      Posted September 30, 2010 at 6:04 am | Permalink

      worked in mozilla but not in IE8
      any solution?
      please tell

    25. Posted October 1, 2010 at 11:14 am | Permalink

      UPDATE: please view the newest post I’ve written about javascript being used to show and hide elements with the help of jQuery tutorial.

    26. Vishu
      Posted November 2, 2010 at 2:21 pm | Permalink

      When I use it more than once on a page it makes ma page go narrow towards the bottom.

      I have used tables from top to bottom. Tables are lined up like this.

      Table 1…. file description…. click it to expand and read more.
      Table 2…. file description…. click it to expand and read more.
      Table 3…. file description…. click it to expand and read more.
      Table 4…. file description…. click it to expand and read more.
      Table 5…. file description…. click it to expand and read more.
      Table 6…. file description…. click it to expand and read more.

      Now my problem is that my page is going narrow at the bottom like this.

      Table 1…………………………
      Table 2…………………….
      Table 3………………..
      Table 4……………
      Table 5……….

      Please help me fix it.

    27. Posted March 9, 2011 at 10:32 pm | Permalink

      Nice site… Thanks

    28. Anna
      Posted March 30, 2011 at 3:14 am | Permalink

      Hello Evan!
      After re-reading this post for hours, I’m afraid I still don’t quite understand. The code doesn’t seem to work for my page. :\
      I’d like to have a toggle box such as hers:
      http://geudae.tumblr.com/
      the “navigation” part. Can you help me with this? Thanks in advance!

    29. Posted May 20, 2011 at 10:21 am | Permalink

      I’m trying to use a script to toggle between alternative blocks of html in a page, each in a different language. For example, there’s a drop-down menu at top which has a list of languages; selecting a language ought to replace the main content section of the page. I know nothing about javascript; what I’ve got so far is purely based on tinkering about with already existing scripts.

                   <script type="text/javascript">
      // code for risk dropdown
      function toggleSubmit(obj){

          count=0
          while(document.getElementById("d"+count)){
          document.getElementById("d"+count).style.display="none"
          count++
          }
          document.getElementById("d"+obj.selectedIndex).style.display="block"

      }
      </script>        
                     
                           
                           <form>

      <select id="riskID" NAME="riskID" onchange="toggleSubmit(this)" style="width: 195px;">
          <option value="">English</option>
          <option value="1">Spanish</option>
          <option value="2">Cymraeg</option>
               <option value="3">Francais</option>
               <option value="4">Deutsch</option>
      </select>
                     
      <!--------BEGIN ENGLISH---->

      <div id="d0">
      English <i>text</i> <a href ="">including code</a>
      <table>
      more html and nested tables
      </table>
      </div>

      <!--------BEGIN SPANISH---->
      <div id="d1" style="display:none">
      Spanish <i>text</i> <a href ="">including code</a>
      <table>
      more html and nested tables
      </table>
      </div>

      <!--------BEGIN WELSH---->
      <div id="d2" style="display:none">
      Welsh <i>text</i> <a href ="">including code</a>
      <table>
      more html and nested tables
      </table>
      </div>

      This kind of works; the page opens, with the English text and links below in place as they should be. When another language is selected, some of the English (before the nested tables) disappears and the other language appears (but below the end of the rest of the page, not in the former position of the English text). I can’t figure out why this should be so.

      Any clue?

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

    • Recent Posts

      WordPress updates plugin directory

      New additions to the plugin directory include: favorites, incorporating support forums into it's own tab for each plugin as well as support stats being displayed! Great! I think we also need the ability to give plugins ratings and reviews (bonus points if it can be done from within a wordpress admin dashboard when installing plugins). [...]

      Short Head

      Use zipf's short head to tune your website rather than redesign the whole thing. To make a website successful it needs to meet the needs of the users. Find out what those needs are by using the short head philosophy to equate most searched things as the biggest needs of the users. Use personas to [...]

      Img Set?

      Great article at a list apart discusing the state of the industry regarding responsive images. This picks apart the set attribute of the img element from a surprisingly objective view coming from someone so close to the picture element. Insightful discussion about the principle behind the proposals than the actual solution too. If the working [...]

      Triudo

      A mesmerizing animated triangle-ish shape form. Embedded Link triduo triduo Tweet

      Git – the paradigm shift

      A great developer story about the differences on what Git is vs other version control and what Git is not. This is how we should learn it. I heard over and over that it was distributed, but never grasped what that meant, so here are a few links and explanations that will help unlearn version [...]

      Tweening Lib comes to Javascript!

      I'm very excited to share the news that the tween library from GreenSock (hands down the best tweening library I used in flash) is not ported for use in javascript! This will be great! I missed that simple syntax from as3 when animating javascript, and now I can have my cake and eat it too. [...]

      Responsive CSS Tricks

      Here are a few useful css tricks to remember when building responsive design sites from web designer wall Embedded Link 5 Useful CSS Tricks for Responsive Design Making the design to be responsive is very easy as shown in my Responsive Design in 3 Steps tutorial, but maintaining the elements to look aesthetically balanced on [...]

      Picture element of srcset attribute?

      Bruce details the reasons and story behind the srcset attribute which is now introduced as an alternative to the picture element. Some aspects of the attribute are nice (like the fact that it's an attribute and not a new element, so it's creating up new elements with for problems. It's adapting currently used elements to [...]

      SVG Preloader with Raphael JS

      Here's a very creative use of using a newly available technology. Using svg graphics which are very lightweight, for a website preloader. I like the animation used as well. Embedded Link Make a stylish preloader with SVG | Tutorial | .net magazine Many sites neglect users with slow connections. Ian Culshaw explains how to use [...]

      CSS3 Button/Icon set

      I've been secretly hoping to see a few of these pop up once the whole icon font idea spread through the nets. I really like this idea and it's a very nice implementation too! I only see some quality issues on a couple of the icons (such as youtube), but it's awesome and I hope [...]

    • Recent Comments

      Bruce Brownlee

      Bruce Brownlee

      Ah IE6. I'd have 2 more years of sleep without IE6. Margin doubling, no properties,...
      versaena

      versaena

      how to give color at runtime…… thank you
      Mobile Websites

      Mobile Websites

      I disagree, mobile websites are the future – desktop websites and mobile websites...
      Matt Fasick

      Matt Fasick

      That's cool. I like the ripple effect as well.
      Nico

      Nico

      hi! really great job guy! very impressive.. just a question… do u have a solution to do a refresh...
      Evan Mullins

      Evan Mullins

      Agreed! I've just seen some people get pretty heated about separating all functionality...