Javascript: Toggle Visibility of Elements

March 9, 2012

Late-night coding sessions allowed me to whip up this quick, reusable snippet.

//Toggle visibility of a given element, specified in the "id" parameter
function toggleNav(id) {
var x = document.getElementById(id).style.display;
if(x == "") {
document.getElementById(id).style.display = 'block';
return false;
else if(x == "block") {
document.getElementById(id).style.display = '';
return false;

This function checks the current value of the display style of the element specified by “id”, then sets it accordingly, i.e., if it is set to “none” (an empty string seems to be JS’s expectations), it sets it into “block” and vice-versa.

You may attach this to an onclick event to a link and set the id parameter to a <div> that has the ‘display: none’ style property. Feel free to reuse this, and/or expand on this code. šŸ™‚

(Of course, this could be done with less effort using jQuery, am I right?)

%d bloggers like this: