Toggle Element Visibility via JavaScript

Post #538 categorized as Function, last updated on Apr 30, 2008
Tagged with javascript, tips, tricks

Recently, while restoring the popular Jupiter! WordPress theme, which several readers use to “skin” the Perishable Press website, I found myself searching for a simple, effective JavaScript technique for toggling element visibility. Specifically, I needed to accomplish the following design goals:

Here are a couple of screenshots demonstrating this repetitious toggling functionality as employed in the Jupiter! theme (click on either thumbnail for larger screenshot):

[ Screenshot: Toggling Metadata (visible state) ]
Click for screenshot showing multiple visible metadata elements

[ Screenshot: Toggling Metadata (hidden state) ]
Click for screenshot showing multiple hidden metadata elements

To accomplish this multiplicity of toggling elements, I employed the following threefold strategy:

1) The Toggle JavaScript

First, I placed a copy of the following toggle-element function into my site’s external JavaScript file:

// Toggle Element Visibility via JavaScript
// http://perishablepress.com/press/2008/04/29/toggle-element-visibility-via-javascript/

function toggle(x) {
	if (document.getElementById(x).style.display == 'none') {
		document.getElementById(x).style.display = '';
	} else {
		document.getElementById(x).style.display = 'none';
	}
}

Once in place, this JavaScript Toggle function takes the target element’s id as a variable and executes the following behavior:

2) The (X)HTML Markup

There are millions of ways to create the markup required for your average “show-hide” scenario. For my particular design needs, I created two divisions ( <div>s ), one containing the toggle link (with class="toggle_link") and another serving as the toggling element (with class="post_meta"):

<!-- division containing the toggle link -->
<div class="toggle_link">
	<a href="javascript:;" onclick="toggle('meta-<?php the_ID(); ?>');" title="Toggle (show/hide) the visibility of meta information for this post">Toggle visibility</a>
</div>

<!-- division serving as the toggling element -->
<div class="post_meta" id="meta-<?php the_ID(); ?>">
	<h4>Posted on <?php the_time('l, F d, Y'); ?></h4>
	<h4>Posted by <?php the_author(); ?></h4>
	<h4>Posted as <?php the_category(','); ?></h4>
</div>

Within the first <div>, the toggle link contains three important attributes:

Note that the id declared as the variable in the toggle function need not be dynamic as specified here. Any statically declared id will work just fine. For example, we could use something like, onclick="toggle('static_id');", or whatever.

Then, within the second <div>, the actual post-meta information is generated and displayed according to various WordPress template tags. The key to this division is the inclusion of the same dynamically generated id as is declared in the onclick="toggle('meta-<?php the_ID(); ?>');" attribute. So long as the id of the toggling element matches that declared in the function call, everything should work exactly as intended.

3) The CSS Presentation

Finally, here is the CSS applied to the toggling division (via class="post_meta"):

div.post_meta {
	display: block;
	width: 133px;
	float: left;
	clear: none;
	padding: 0;
	margin: 0;
	}

Of course, you will want to style your markup differently, however I include these styles as example and for the completion of this tutorial. For my particular design, the inclusion of the display: block; property ensures that the meta information is displayed by default and also when JavaScript is unavailable.

Wrap up..

As many of you know, there are a million ways to show and hide divisions and other elements via JavaScript. By no means I am suggesting that this technique is like the most absolute bestest method ever. The same may be said for the markup and CSS. This tutorial is intended to further understanding of toggling in general by way of a specifically applied example. This specific application works great for me, and hopefully will be adapted and extrapolated to suit the needs of others. Having said that, I realize that various aspects of the method are less than perfect, so feel free to share your insights and wisdom with the community. Cheers! :)

Subscribe to Perishable Press


4 Responses

TopLeave a comment

[ Gravatar Icon ]

#1teddY

Thank you so much for sharing this! I’ve never realised that you can actaully incorporate PHP codes within javascript commands - which is going to be very useful! Although Scriptaculous or Moo.fx gives cooler effects, I guess the script you’ve provided is extremely lightweight and dialup friendly. Plus, it’s very easy to implement as well!

[ Gravatar Icon ]

#2Perishable

Yes, that is precisely the point with much of the code that I share here at Perishable Press. As you may have guessed looking at the site’s current design, I am way into easy, no-frills approaches and minimalistic design functionality. You are totally right, however, about there being “cooler” effects available, and I intend to explore some of the “newer tricks” with the imminent development of future projects. All in good time, my friend! ;)

Share your thoughts..

TopRead official comment policy

The rules are simple. Comment intelligently. Stay on-topic. Don’t spam! Suspected spam will be deleted. Use your real name or nickname, not a site name or business name. Using a site name or business name is a good way to get your link or comment removed. Certain comments are moderated; if your comment does not appear after several days, or if you wish to comment privately, contact me. Also, by posting a comment, you grant this site a perpetual license to reproduce your comment, name, and website URL. Lastly, you may use basic HTML markup, but please do not use <pre> tags. Instead, wrap your code with <code> tags. Use a new set of <code> tags for each code term or phrase, as well as for each individual line of code (i.e., multiple lines of code require multiple code tags). Please see the complete comment policy for more information.