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>
    <script language="javascript">
        function MyFunction(divName){

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

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

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

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

        }
    </script>
    <input id="tempDivName" type="hidden" />
    <ul>
        <li><a href="#" OnClick="MyFunction('myDiv1');">Show myDiv1</a></li>
        <li><a href="#" OnClick="MyFunction('myDiv2');">Show myDiv2</a></li>
        <li><a href="#" OnClick="MyFunction('myDiv3');">Show myDiv3</a></li>
    </ul>
    <br/>
    <div id="myDiv1" style="background-color:red; height:200px; width:200px; display:none">
        myDiv1
    </div>
    <div id="myDiv2" style="background-color:yellow; height:200px; width:200px; display:none">
        myDiv2
    </div>
    <div id="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/

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

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

    //handle click events
    function toggleVisible() {
        //hide currently shown item
        document.getElementsByClassName('show')[0].classList.remove('show');
        //show clicked item
        this.classList.add('show');
    }
</script>

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