Find currently visible div in jquery

ACP picture ACP · Jul 23, 2010 · Viewed 14.4k times · Source

I have a four divs all set display:none and on document.ready i am showing the first div.. I have 4 link buttons link1,link2...link4... I showing div1 on link1 click and so on.. How to find which div is currently visible in jquery?

 <style type="text/css">
        .ContentDivs
        {
            width: 90%;
            height: 300px;
            border: solid 5px #404040;
            display:none;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <a id="Link1" href="#">Link1</a> 
            <a id="Link2" href="#">Link2</a>
             <a id="Link3" href="#">Link3</a> 
             <a id="Link4" href="#">Link4</a>
        </div>
        <div id="div1" class="ContentDivs">
        DIv1
        </div>
        <div id="div2" class="ContentDivs">
        Div2
        </div>
        <div id="div3" class="ContentDivs">
        Div3
        </div>
        <div id="div4" class="ContentDivs">
        Div4
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
              $("#div1").show().fadeIn("slow");
        });
        $('#Link1').click(function() {
        $(".ContentDivs").fadeOut("fast");//find current div here?
            $("#div1").show().fadeIn("slow");
        });
        $('#Link2').click(function() {
        $(".ContentDivs").fadeOut("fast");//find current div here?
            $("#div2").show().fadeIn("slow");
        });
        $('#Link3').click(function() {
        $(".ContentDivs").fadeOut("fast");//find current div here?
            $("#div3").show().fadeIn("slow");
        });
        $('#Link4').click(function() {
        $(".ContentDivs").fadeOut("fast");//find current div here?
            $("#div4").show().fadeIn("slow");
        });
    </script>

See the effect here http://jsbin.com/umode4/edit

Answer

Reigel picture Reigel · Jul 23, 2010

with lesserr codes, you could do it this way...

jQuery

<script type="text/javascript">
    $(document).ready(function() {
          $("#div1").show().fadeIn("slow");
    });
    $('.links a').click(function() {
        $(".ContentDivs:visible").fadeOut("fast");//find current div here?
        $("#div" + ($(this).index()+1)).show().fadeIn("slow");
    });
</script>

html

<div>
    <div class="links">
        <a id="Link1" href="#">Link1</a> 
        <a id="Link2" href="#">Link2</a>
        <a id="Link3" href="#">Link3</a> 
        <a id="Link4" href="#">Link4</a>
    </div>
    <div id="div1" class="ContentDivs">
        DIv1
    </div>
    <div id="div2" class="ContentDivs">
        Div2
    </div>
    <div id="div3" class="ContentDivs">
        Div3
    </div>
    <div id="div4" class="ContentDivs">
        Div4
    </div>
</div>

demo