views:

30

answers:

1

In this javascript hide/show example, how can I close all other divs when a div is selected?

 <script TYPE="text/JavaScript">
    function show_hide(id, show)
    {
      if (el = document.getElementById(id))
      {
        if (null==show) show = el.style.display=='none';
        el.style.display = (show ? '' : 'none');
      }
    }
    </script>

& don't tell me to use jQuery, becuase it won't run in some mobile environments that we use.

+1  A: 

I'd do it like this

var alldivs = document.getElementsByTagName("DIV");
for (var i=0;i<alldivs.length;i++){
 var odiv = alldivs[i];
 //we only need "other" divs, not the one we're working on
 if ( (odiv.id) && (odiv.id!=id)) {
   odiv.style.display="none";
 }
}

(+ thanks for not asking for a jQuery solution:)

naivists
works perfectly as described!
robert