Expand and Collpase of DIV using jQuery

Expand Collapase of a DIV

The element DIV can be made hidden and visible by using style attribute of display to none and block.The action is so fast that the end users may not be pleaased with that kind of action.

New approach using jQuery

The effect of collpase and expand of these DIV element as you are experiencing here is made by using jQUery. jQuery has a function called slideToggle which is good enough for this kind of action.

Where is the code

You need to define stylesheet for the following elements.
        p
        {
            margin:0px;
        }
        .msg_list
        {
            margin: 0px;
            padding: 0px;
            width: 99%;
        }
        .msg_head
        {
            padding: 5px 10px;
            margin: 1px 0;
            cursor: pointer;
            position: relative;
            background-color: #313131;
        }
        .msg_body
        {
            padding: 5px 10px;
            background-color: #717171;
        }
            
You need to design your html part in the foloowing manner.
        
        <div class="msg_list">
            <p class="msg_head">
                Message Header
            </p>
            <div class="msg_body">
                Body Message for the above header
            </div>
            <p class="msg_head">
                Message Header</p>
            <div class="msg_body">
                Body Message for the above header
            </div>
            <p class="msg_head">
                Message Header</p>
            <div class="msg_body">
                Body Message for the above header.
            </div>
        </div>
        
        
Finally the jQuery Code,
    <script type="text/javascript">
    $(document).ready(function(){
        //hide the all of the element with class msg_body
        $(".msg_body").hide();
        //toggle the componenet with class msg_body
        $(".msg_head").click(function(){
            $(this).next(".msg_body").slideToggle(200);
        });
    });
    </script>
            
and dont forget to include jQuery.js in page's <head> tag.

No  Responses to "Expand and Collpase of DIV using jQuery"

Leave a Reply