Question

I am making a dynamic page that holds 3 different div's (might increase, but 3 for now). They are hidden at first, but when a link is clicked the div chosen will appear. I got this working, but now the problem I am having is that I don't really know how to get started on making it remember what div is open, then close the open one and open the newly picked one.

So basically to give an idea of what I want to happen:

  • Click a link to open a div1
  • Div1 opens and gets displayed
  • Click the link to open div2
  • Div1 closes, and div2 will display
  • Click div1 link again
  • Div2 will close, and div1 will open
  • Click div1 link yet again
  • Div 1 will close

What I got so far is the opening/closing, but I don't know how to do the "remembering" part pretty much, since I'm not that experienced with jQuery. Inside the code you will see the link is linked to "#", I'm also wondering how to make the page "flow" to the div selected (which is lower on the page).

I posted my code on the following pastebin link: http://pastebin.com/psftzriY

Thanks ahead!

<html>

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $('#div1toggle').click(function() {
                $('.div1').slideToggle("slow");
        });
    });
    $(document).ready(function() {
        $('#div2toggle').click(function() {
                $('.div2').slideToggle("slow");
        });
    });
    $(document).ready(function() {
        $('#div3toggle').click(function() {
                $('.div3').slideToggle("slow");
        });
    });
</script>

</head>

<body>

<a href="#" id="div1toggle">Click here DIV1</a><br>
<a href="#" id="div2toggle">Click here DIV2</a><br>
<a href="#" id="div3toggle">Click here DIV3</a><br>

<div class="div1" style="display:none;">
   <h1>Div1</h1>
   <p>Text</p>
</div>

<div class="div2" style="display:none;">
   <h1>Div2</h1>
   <p>Text</p>
</div>

<div class="div3" style="display:none;">
   <h1>Div3</h1>
   <p>Text</p>
</div>


</body>

</html>
Was it helpful?

Solution

Check : http://jsfiddle.net/hamidlab/xLzjZ/1/

Hide all divs and then show the targetDiv. If targetDiv is :visible, hide it.

OTHER TIPS

Get display property of the element.

$('#div1toggle').css('display');

Check its none Or blcok

I would add a class to the open div, that way it is easy to find again:

//Hide the existing div and remove the class
$(".open-div").hide();
$(".open-div").removeClass("open-div");

// Now show the div that was just clicked and add the class 
myClickedDiv.show();
myClickedDiv.addClass("open-div");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top