Javascript Code to show a hidden element | Display and Visibility

Google Buzz

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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";
  }
}
1
2
<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

  • del.icio.us
  • Digg
  • email
  • Facebook
  • FriendFeed
  • Google Bookmarks
  • Hexosearch
  • LinkedIn
  • Mixx
  • Print
  • PDF
  • StumbleUpon
  • Technorati
  • Twitter
  • RSS
This entry was posted in tutorial and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

21 Comments

  1. n00bie
    Posted 16 January 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 16 January 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 16 January 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 13 February 2008 at 11:31 am | Permalink

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

  5. Sumant
    Posted 29 April 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 12 May 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 13 May 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

    1
    2
    3
    4
    5
    6
    7
    8
          function toggleVisibility() {
          if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
          document.getElementById("toggleMe").style.visibility = "visible";
          }
          else {
          document.getElementById("toggleMe").style.visibility = "hidden";
          }
          }
    1
    2
          <p onclick="toggleVisibility();">Click to toggle.</p>
          <p id="toggleMe" style="visibility: hidden"> Something to Hide, but still affects layout.</p>
  8. Posted 13 May 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 28 May 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 29 May 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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    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.

    1
    2
    3
    4
    5
    6
    7
    <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

  11. Posted 26 June 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 26 June 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 1 July 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 18 July 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 19 July 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 20 July 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 3 May 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 7 May 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 11 November 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 ….

    Set up a context call

    Context call is a meeting/call set up between the Requestors (Functional Team) and the Request Manager to discuss the scenarios requested.
    Request Managers can use this call for finalizing the priority of the requests as well.

    The Context call has to be documented and to be placed in the Share drive.
    It should have details like
    1.Date and time of the call,
    2.Participants,
    3.Brief outline of discussion etc.

    The context call tracker has to be filled by the RM after the completion of context call.
    This includes the action item on the requestors and the Request Manager discussed during the call.
    Requirement Query Tracker: Any discussions/Action items on DM team/Functional team carried out during the progress of the job should be updated in the requirement query tracker.

  19. jojo
    Posted 3 February 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…

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=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>