user1658756
user1658756

Reputation: 1024

Hiding and Showing Elements with JavaScript or jQuery

I have an arrow on my site that I'd like if onclick, it hides one element, and shows another. Hitting it again, will hide the element that was shown and show the element that was hidden.

For example, I have

<div id="arrow"><a href="#">▾</a></div>

<div id="ad"></div>

<div id="description">Hidden</div>
<div id="nav">Also Hidden</div>

So at first, the ad is showing, and then one you've clicked the arrow, I'd like the ad to hide, and then unhide the description and nav.

Upvotes: 0

Views: 522

Answers (3)

The Alpha
The Alpha

Reputation: 146191

Try this (Since you asked for plain javascript)

window.onload=function(){
    var arrow=document.getElementById('arrow').getElementsByTagName('a')[0];
    arrow.onclick=function(){
        var ad=document.getElementById('ad');
        var description=document.getElementById('description');
        var nav=document.getElementById('nav');
        if(ad.style.display=='none')
        {
            ad.style.display='block';
            description.style.display='none';
            nav.style.display='none';
        }
        else
        {
            ad.style.display='none';
            description.style.display='block';
            nav.style.display='block';
        }
        return false;

    };
};

DEMO.​

Upvotes: 1

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91309

With jQuery, use .toggle():

$("#arrow").click(function () {
   $("#ad, #description, #nav").toggle();
});​

DEMO.

With plain JavaScript, you need to toggle the display property of each element manually:

document.getElementById("arrow").onclick = function () {
    var description = document.getElementById("description"); 
    var nav = document.getElementById("nav"); 
    var ad = document.getElementById("ad");
    if (ad.style.display == 'none') {
      ad.style.display = '';
      nav.style.display = 'none';   
      description.style.display = 'none';
    } else {
      ad.style.display = 'none';
      nav.style.display = '';   
      description.style.display = '';
    }
};​​​​​​

DEMO.

Upvotes: 4

codingbiz
codingbiz

Reputation: 26386

DEMO

   ​​ <input id="x" value="x" />
    <input id="y" value="y" style="visibility:hidden" />
    <input type="button" onclick="toggleBoth()" value="arrow" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

.

function toggle(id){

  var elem = document.getElementById(id);

    if(elem.style.visibility == 'hidden')
        elem.style.visibility = 'visible';
    else
      elem.style.visibility = 'hidden';  
}

 function toggleBoth()
    {
       toggle('x');
       toggle('y');
    }
​

Upvotes: 0

Related Questions