Monday, November 7, 2011

JQuery to Show Hide (toggle) Multiple Divs

 

 

This article displays how to implement JQuery to show/hide (toggle) multiple Divs with image indicator.

 

First let us see the the Jquery fucntion.

 

<script language="javascript" type="text/javascript" src="JS/jquery-1.6.4.min.js"></script>

 

<script type="text/javascript">

        $(document).ready(function() {

            $('.bodyCls').hide();

            $('.show').click(function() {

                imgelem = $(this);

                $(this).parent().next().slideToggle("fast", function() {

                    //alert($(this).css("display"));

                    if ($(this).css("display") == "none") {

                        imgelem.attr("src", "Images/expand.gif");

                    }

                    else {

                        imgelem.attr("src", "Images/collapse.gif");

                    }

                });

            });

        });

    </script>

 

This CSS is not mandatory, however, this will give better look and feel.

<style type="text/css">

        div.headerCls

        {

            height: 30px;

            background-color: #5797E9;

            font-family: Verdana;

            font-size: 10pt;

            font-style: normal;

            font-weight: bold;

            color: White;

        }

        div.bodyCls

        {

            height: 50px;

            background-color: #CCFFFF;

        }

        img.show

        {

            float: right;

            vertical-align: middle;

        }

    </style>

 

The HTML divs required

<body>

    <form id="form1" runat="server">

    <div style="width: 60%; margin: 25px auto;">

        <div id="header1" class="headerCls">

            Header 1

            <img class="show" src="Images/expand.gif" alt="Show/Hide" /></div>

        <div id="body1" class="bodyCls">

            Body 1</div>

        <div id="Div1" class="headerCls">

            Header 1

            <img class="show" src="Images/expand.gif" alt="Show/Hide" /></div>

        <div id="Div2" class="bodyCls">

            Body 1</div>

        <div id="Div3" class="headerCls">

            Header 1

            <img class="show" src="Images/expand.gif" alt="Show/Hide" /></div>

        <div id="Div4" class="bodyCls">

            Body 1</div>

    </div>

    </form>

</body>

 

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://www.w3schools.com/jquery/default.asp

 

1 comment: