Skip to content Skip to sidebar Skip to footer

Hiding A Div When Another Is Shown

So, I have a nav element with an unorder list that I use as tabs. There are three, you click one and it shows a div in the website. However, I want it so that if you click anothe

Solution 1:

also you can store the DIV name in a Hidden Input

http://jsfiddle.net/we2AJ/

<body><scriptlanguage="javascript">functionMyFunction(divName){

        //hidden valvar hiddenVal = document.getElementById("tempDivName"); 

        //hide oldif(hiddenVal.Value != undefined){
            var oldDiv = document.getElementById(hiddenVal.Value); 
            oldDiv.style.display = 'none'; 
        }

        //show divvar tempDiv = document.getElementById(divName); 
            tempDiv.style.display = 'block';              

        //save div ID
            hiddenVal.Value = document.getElementById(divName).getAttribute("id");

        }
    </script><inputid="tempDivName"type="hidden" /><ul><li><ahref="#"OnClick="MyFunction('myDiv1');">Show myDiv1</a></li><li><ahref="#"OnClick="MyFunction('myDiv2');">Show myDiv2</a></li><li><ahref="#"OnClick="MyFunction('myDiv3');">Show myDiv3</a></li></ul><br/><divid="myDiv1"style="background-color:red; height:200px; width:200px; display:none">
        myDiv1
    </div><divid="myDiv2"style="background-color:yellow; height:200px; width:200px; display:none">
        myDiv2
    </div><divid="myDiv3"style="background-color:green; height:200px; width:200px; display:none">
        myDiv3
    </div></body>

Solution 2:

You can improve the structure of this code by leveraging css classes. First, use getElementsByClassName to gather all your nav items. Then attach a click handler to them that points to your toggle code.

In the togglecode, add a class for the shown element and remove it for the old one. I made assumptions about your html structure, but this should be easily adaptable. classList isn't supported by < IE7, but you can substitute in a regex to handle this if support is necessary.

http://jsfiddle.net/8Q4vy/1/

<divclass="nav show"><span>A</span></div><divclass="nav"><span>B</span></div><divclass="nav"><span>C</span></div><script>//get nav itemsvar navElems = document.getElementsByClassName('nav');

    //attach click handler to eachfor (var i = 0; i < navElems.length; i++) {
        navElems[i].onclick = toggleVisible;
    }

    //handle click eventsfunctiontoggleVisible() {
        //hide currently shown itemdocument.getElementsByClassName('show')[0].classList.remove('show');
        //show clicked itemthis.classList.add('show');
    }
</script>

Post a Comment for "Hiding A Div When Another Is Shown"