JavaScript to hide all DIVs on page and show a specific DIV


Go to this page to see the solution posted on Webdeveloper.com. The solution below is modifed from what was posted. IMO, this is cleaner than what I opriginally posted.


Two DIVs are displayed below.
 

DIV ID=one

DIV ID=two


<div id="one" style="border:solid 1px black;width:150px;background-color:#faebd7;"><p>DIV ID=one</p></div>

<div id="two" style="border:solid 1px black;width:150px;background-color:#ffe4c4;"><p>DIV ID=two</p></div>


When you click links "Show/Hide DIV ID=one" or "Show/Hide DIV ID=two", each DIV will either disapper or appear.

If you click "Show/Hide DIV ID=three", since there is no DIV with id=three, nothing happens. The good thing about this is that there is no error when trying to hide an object that does not exist on the page.


Here is the JavaScript function. It accepts 2 parameters. The first is the ID of the element that you are trying to change. The second is either "flip", or whatever style you want to assign to the element. "flip" toggles the element from "block" to "none" and back.


function safeToggleFieldDisplay(field, sVisibility){

  try{

    if((field) && (field.style)){

      if (sVisibility=='flip'){

        if (field.style.display == 'none'){

          sVisibility = 'block'; }

        else {

          sVisibility = 'none'; }

      }

      field.style.display = sVisibility;

    }

  }

  catch(exception){

    //no handling - just preventing page explosions

  }

}