Toggle Element Visibility via JavaScript
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:
- Users should be able to toggle the visibility of any division containing post-meta information
- The post-meta information should remain visible by default and when JavaScript is unavailable
- The JavaScript should be as unobtrusive as possible, requiring minimal scripting in the markup
Here are a couple of screenshots demonstrating this repetitious toggling functionality as employed in the Jupiter! theme (click images for larger view).
Here is how I accomplished this multiplicity of toggling elements:
Step 1: Add JavaScript
First, I placed a copy of the following toggle-element function into my site’s external JavaScript file:
// Toggle Element Visibility via JavaScript
// https://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:
- The toggle function first checks the CSS
display
style associated with the target toggling element. - Then, if the element’s
display
property is declared asnone
, the toggle function discards the property and displays the element. - Otherwise, if the element’s
display
property is declared as anything other thannone
(e.g.,block
,visible
, etc.), the toggle function switches the property tonone
and hides the element.
Step 2: Add HTML
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:
href="javascript:;"
— instructs the browser to ignore the link and execute the JavaScript.onclick="toggle('meta-<?php the_ID(); ?>');"
— triggers the JavaScript and passes the dynamically generated elementid
to the toggle function.title="Toggle (show/hide) the visibility..."
— explains the purpose of the link and indicates what to expect if clicked.
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.
Step 3: Add CSS
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! :)
4 responses to “Toggle Element Visibility via JavaScript”
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!
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! ;)
Here is the only way I’ve found to:
* Toggle Multiple Div with identical ID’s , using the same link
function showhide(id) {var tags = document.getElementsByTagName('div');for (var i = 0; i < tags.length; i++) {if (tags[i].id == id) {tags[i].style.display = (tags[i].style.display == 'none') ? '':'none';}}}
* using this to call it:
(a onclick="showhide('show');return false;")Show/Hide(/a)
– i.e. — ‘show’ is the id of the div’s
SS –
after more than an hour of trying, i am asking for help.
in your contribution of jan 15 2011 you wrote some code to close multiple divs of the same id.
i can’t get it to work. i have my divs of the same id, and i see your show/hide link, but it’s no go.
i am not brand new to this, but have been at it for about 3 months only. i am hoping that making this code work can help me with a more complicated issue i am trying to figure out (showing & hiding videos, like a gallery).
a little advice would be welcome.
pat