1

I have the following code, for enabling a div from toggling between visible and hidden:

function toggle_visibility(id,$this) {
  var e = document.getElementById(id);
   if(e.style.display == 'block')
   {
     e.style.display = 'none';
   }
   else
   {
     e.style.display = 'block';
   }
}

Basically when I click a link that has onclick="toggle_visibility('4s'); within it then the specified div is shown and then when you click again it is hidden.

My problem is when the same code is use for multiple links, and you toggle the visibility of one and then the other, the previous one is still shown. How would I go about only enabling one div to be shown when toggled and then if another is toggled the other is hidden?

namuol
  • 9,816
  • 6
  • 41
  • 54
Alex Saidani
  • 1,277
  • 2
  • 16
  • 31

3 Answers3

3

Keep a global variable for the div which is currently visible and make it invisible when you make any div visible.

var previousVisibleElement;
function toggle_visibility(id,$this) {
  var e = document.getElementById(id);
  if(e.style.display == 'block')
   {
     e.style.display = 'none';
  }
  else
  {
     if(previousVisibleElement !=null)
          previousVisibleElement.style.display='none';
     e.style.display = 'block';
    previousVisibleElement=e;

  }
}
Shamaila Tahir
  • 988
  • 2
  • 8
  • 17
2

Here is a generic example using jquery.

Markup

<section>
    <div id="1">one</div>
    <div id="2">two</div>
    <div id="3">three</div>
    <div id="4">four</div>
</section>
<a href="#1">one</a>
<a href="#2">two</a>
<a href="#3">three</a>
<a href="#4">four</a>

JS

var divs = $('section div'),
    links = $('a');

links.click(function(){
    $(this.hash).toggle().siblings().hide();
    return false;
});
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • 3
    But the OP did not ask for a jQuery solution. – Sparky Oct 12 '11 at 17:09
  • 1
    The question was tagged with jQuery originally . – Josiah Ruddell Oct 12 '11 at 18:19
  • Thanks for the response, I can see it works perfectly on jsfiddle with the link you sent. However when I put the exact same code onto a php file with the jquery file included it does not seem to work, not sure what the problem could be? – Alex Saidani Oct 12 '11 at 22:03
  • You most likely need a better selector. In the fiddle example there were only 4 links on the page, so `$('a')` was fine. You can add a class to the links, and select them by class name `$('a.some-class')` to scope the selector. – Josiah Ruddell Oct 12 '11 at 22:40
0

if you provide the current script in a jsfiddle people would be able to answer better.

here is a small sample i did using jquery. hide using jquery toggle