Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/hide divs with same class

Tags:

jquery

I have four images and four divs. When image 1 is clicked, div 1 should appear and all others should be hidden, etc. Each div has the same class name.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Untitled 1</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
    $(window).load(function(){
        $(".DataList").hide();
        $(".DataList:first").show();    
        $(".trigger").click(function() {
            $(".DataList").hide();
            $(".DataList").eq($(this).index()).show();
        });
    });
</script>
</head>

<body>

<div id="LinkBar">
    <table border="0">
        <tr>
            <td>
               <a class="trigger" href="#"><img src="Package1.gif" /></a> </td>
            <td>
               <a class="trigger" href="#"><img src="Package2.gif" /></a> </td>
        </tr>
    </table>
</div>

<div class="DataList">
    <div class="Description">
        <ul class="Package">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
        <div class="Hidden">
            1 </div>
    </div>
</div>

<div class="DataList">
    <div class="Description">
        <ul class="Package">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
        <div class="Hidden">
            2 </div>
    </div>
</div>

</body>

</html>
like image 846
YBW Avatar asked Aug 09 '26 16:08

YBW


1 Answers

Edited, based on your full markup:

$(".DataList").hide();
$(".DataList:first").show();
$(".trigger").click(function() {
    $(".DataList").hide();
    $(".DataList").eq($(this).closest("td").index()).show();
});

The above solution relies on the cell index in which the .trigger links appear.

Try it here

See:

  • http://api.jquery.com/closest/
  • http://api.jquery.com/eq/
  • http://api.jquery.com/eq-selector/
  • http://api.jquery.com/index/
like image 81
karim79 Avatar answered Aug 11 '26 05:08

karim79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!