PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » JavaScript » Toggle (Show/Hide) Element

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

Subscribe to The Thread

  1. 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. the only problem i have with it is what i have to click the link twice the first time to make it disappear.

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

  3. 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.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~