October 28, 2007

Show/Hide Content With CSS & Javascript

Filed under: CSS — Matt @ 1:51 am

My apologies for the recent lack of updates and the briefness of this post, things have been (and still are) really busy on my end. Anyway, when building websites for my clients a popular request is to have content that can be toggled by the user. Today I’ll show you have to have this effect done really quickly. Although this method does not support persistence (saving cookies to the users browser to remember what they have hidden/shown), I’m sure there are some who will find it useful.

Place this code in your <head> tags.

<script type=”text/javascript”>
function shToggle(content) {
if (document.getElementById(content).style.display == “none”)
document.getElementById(content).style.display = “block”
else
document.getElementById(content).style.display = “none”
}
</script>

Now you can effectively show/hide content by placing id=”elementname” style=”display:none;” inside the element tag you wish to be toggle-able, and onclick=”shToggle(’elementname‘); return false;” inside the link code of the image or text the user clicks to toggle it. You can see a live example of it on this page, or simply look at the example code snippet below.

<strong>What’s the name of Calgary’s NHL Team?</span>
<a href=”javascript:void(0);” onclick=”shToggle(’calgary’); return false;”>show/hide answer</a>

<div id=”calgary” style=”display:none;”>The Calgary Flames</div>

3 Comments »

  1. I use a similar script in my pages. To extend this script to toggle other elements (such as a table row) you need to set the display style to it’s own setting. I.e. a tr will need to be set to ‘table-row’, a td to ‘table-cell’ etc. See http://www.w3schools.com/css/pr_class_display.asp for other options.

    However, this throws an error in IE. So you need to either put each statement in a try/catch block, or be more clever about browser detection to determine the correct method.

    Comment by Neon Knight — October 31, 2007 @ 4:23 pm

  2. kinda ‘cheap but you can also do:

    document.getElementById(’DIV_ID’).innerHTML=”;

    Comment by Jesse — November 8, 2007 @ 7:28 pm

  3. I search more than 1 hour for this.
    Really thanks.

    Comment by Moin Uddin — November 18, 2007 @ 6:01 am

RSS feed for comments on this post. TrackBack URL

Leave a comment