How to toggle display of page elements with JavaScript

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to toggle display of page elements with JavaScript

Post by Neo » Mon Mar 01, 2010 1:29 am

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:

Code: Select all

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.

Code: Select all

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.

Code: Select all

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.

Code: Select all

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:

Code: Select all

<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:

Code: Select all

<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>
Post Reply

Return to “Web programming”