Wednesday, June 01, 2005

Javascript: Display Toggle

Had to really think this through to get it to work like I wanted. Fairly elegant in the end, thanks to the fact that variables within a JS function effectively act as static when the page is not reloaded. The code:

<!-- JS: SHOW/HIDE FUNCTION -->
<script type="text/javascript">
<!--
toggle_count = 0;

function toggle_button(element_id) {
toggle_count++;
show = toggle_count % 2;
show_hide(show, element_id);
return;
}

function show_hide(show, element_id) {
if ( show == 1 ) {
document.getElementById(element_id).style.display = '';
} else {
document.getElementById(element_id).style.display = 'none';
}
return;
}
//-->
</script>


Then call like so using the id you've given to the doc element:

<a onclick="toggle_button('element name')" href="#">show/hide element</a>


An example can be seen here by hitting "show creative process" link on results page. (Only tested in Firefox.)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home