UltraMega Blog
15Dec/082

Toggle Display of Page Elements with JavaScript

This mini tutorial explains how to show/hide elements on a web page using JavaScript. There are many reasons why you would want to do this, and luckily it is very simple.

All it takes is changing the display CSS property. Setting display: block; (the default for div tags) makes it visible, and display: none; makes it hidden. The advantage to using display is that other items on the page will move to close the void left by the hidden object.

Fist, we'll start with creating the function:

function toggleDisplay(id) {
 
}

We will call this function, passing the id of the targeted object. We now need to get a handle of the object identified.

function toggleDisplay(id) {
   var obj = document.getElementById(id);
}

Now that we have the object, we need to check what display is currently set to. We will then change it accordingly.

function toggleDisplay(id) {
   var obj = document.getElementById(id);
   if(obj.style.display == 'none') {
      // show the object
   } else {
      // hide the object
   }
}

As you can tell, accessing CSS properties is done using object.style.property, replacing "property" with the desired property. Changing is as easy as changing a variable.

1
2
3
4
5
6
7
8
function toggleDisplay(id) {
   var obj = document.getElementById(id);
   if(obj.style.display == 'none') {
      obj.style.display = 'block';
   } else {
      obj.style.display = 'none';
   }
}

That's all there is to the JS function!

Now to use it, we just need to call the function with a link, button, or any event. For example:

<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>

When the user clicks the link, it will call the function. I also added return false; to the event to stop the browser from following the link (prevents the page scrolling up).

Here is the whole example page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
<title>Toggle Display</title>
<script type="application/javascript" language="javascript">
function toggleDisplay(id) {
   var obj = document.getElementById(id);
   if(obj.style.display == 'none') {
      obj.style.display = 'block';
   } else {
      obj.style.display = 'none';
   }
}
</script>
</head>
<body>
<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>
</body>
</html>

Thanks for reading, I hope this was helpful!

Posted by Steve

Comments (2) Trackbacks (1)
  1. Hey Steve,

    I was looking for a simple JS that would let me do the toggling, and I am glad I found this and its by far the simplest tutorial I have come across.

    Thank you.

  2. not working with ie, working fine with firefox


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.