Javascript toggle function
June 09, 2007
Most Popular | Javascript | Snippets

One of the most frequently used constructions in javascript are functions that toggle styles or properties on and off. This can be used for items that require a highlighting effect, or to create layers that expand or contract, or any other property change where you want a property of an element to toggle on and off depending on its current state.

Put this in the head of the document:
 <script>function toggle(id){ 
  var element = document.getElementById(id); 
  element.style.display = (element.style.display == 'block') ? "none" : "block"; 
  } 
 </script> 

Create the trigger for the toggle:
<a href="javascript: toggle('myElement');">Open/Close</a>

Create the element you want to toggle open and closed:
<div id="myElement" style="display:block"> content goes here </div>


Ads by Google

Posted by ellen at June 09, 2007 10:56 AM

5 Comments

I would like to know about the loading of java script as well as VB script.Are they live in the Internet explorer software which is loading in the computer or loading by other disk. thank you

Hi ashok, when they are downloaded along with the HTML code and interpreted by the browser, they are considered to be "client-side" scripts. Both can be also used as server-side scripting languages when used in .asp or .jsm, etc. In that case they are interpreted by the server, before the HTML page is generated and downloaded to the browser.

Take a look at the wikipedia article on JavaScript for more information.

(element.style.display == 'block')

Correct one should be........

(element.style.display = 'block')

Still doesn't toggle. Am I doing something wrong? And what if we need to use it more than once on a page?

Hi mate.... I got it now. Thanx for the clarification. It works :)

To use it more than once just write diffrent triggers.... Have a look.

Create the trigger for the toggle:
Open/Close

Create the element you want to toggle open and closed:
content goes here


Create the trigger for the toggle:
Open/Close

Create the element you want to toggle open and closed:
content goes here

And like this A, B, C .... you can add as many you want. This blog solved a big problem for me. THnx a lot :) I am happy I visited ur site. Take care.


Ads by Google

 RSS   |   Contact Me

Ads by Google

Ads by Google