Search code examples
jqueryhtmlhideshowoverlapping

jQuery multiple divs show hide only one at a time


Hello and let me first explain that I have not used jQuery very much at all. Simple show and hide and basic UI is the extent. So with that said, I am trying to be able to show a div, that is actually a "page" that has been linked to a "link".

Markup:

<body>
<!--Footer and Navigation Div's-->
<div id="bg"><img src="images/bg.jpg" alt=""></div>
    <div id="footer">
        <p>S.E. <span>yoga</span></p>
            <div id="nav">
                <ul><a href="#">Link 1</a></ul>
                <ul><a href="#">Link 2</a></ul>
                <ul><a href="#">Link 3</a></ul>
                <ul><a href="#">Link 4</a></ul>
            </div>
    </div>
<!--END Footer and Navigation Div's-->

<div class="parent">
<div class="a">
        <p>this is a</p>
    </div>   
   <div class="b">
        <p>this is b</p>
    </div>
    <div class="c">
        <p>this is c</p>
    </div>
    <div class="d">
        <p>this is d</p>
    </div>
</body>
</html>

jQuery:

 /*
 $(document).ready(function(){
 $('#nav').click(function(){
        $(".a").slideToggle();
  var divname= this.value;
          $("#"+divname).show("slow").siblings().hide("slow");

    });
});*/ 

    $(document).ready(function(){
    $('.a, .b, .c, .d').hide();
});;

So the first script (commented out) I was using I was going to use as a starting point. The second script, where they are all hidden is where I was going to go from. Hide them all, then show only one at a time.

The divs are overlapping. Any help? Thanks!


Solution

  • You can use this

     $(document).ready(function(){
             $('.parent  div').hide(); // hide div's on load using parent class as a starting point     
             $('#nav a').click(function() {  // on the anchor clicks that are inside div with id=nav
                var $div = $('.parent div').eq($(this).index('#nav a'));  // get the relevant div
                $div.show();  // show the relevant div
                $('.parent div').not($div).hide();  // hide all but the relevant div
            });​
        }):
    

    EDIT:

    $('.parent div') // <-- this gets all divs under the element with class parent

    .eq(index) // will get the element at the given index which is the following

    $(this) // <-- Current clicked anchor tag

    .index('#nav a'); // <-- get the index() of the current anchor tags compared to other other anchor tags

    weird thing is I usually use $(this).index() and it works but this time it didn't so I had to specify a selector inside the index.

    also fix your html to look like this instead

     <div id="nav">
        <ul>
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
            <li><a href="#">Link 4</a></li>
        </ul>
    </div>
    

    Updated fiddle

    http://jsfiddle.net/HpCWW/1/