Skip to content Skip to sidebar Skip to footer

Toggling Visibility Of Divs Using Javascript

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.

Solution 1:

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;

  }
}

Solution 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;
});

Solution 3:

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


Post a Comment for "Toggling Visibility Of Divs Using Javascript"