Toggle Ordered/ Unordered List Using jQuery

So let us say you have a tree like structure created with a bunch of <ul> and <li>. Now you come across a requirement where you need to expand and collapse these sections. Let us see how to do this using jQuery (tested on IE and Firefox)


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>    

    <style type="text/css">

        .clsUL

        {            

            cursor:hand;

        }

    </style>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript">

    </script>

 

    <script type="text/javascript"> 

        $(document).ready(function(){

        $('#unord li').click(function() { 

                    $(this).children('ul').slideToggle("slow"); 

            }); 

        });

    </script>

 

</head>

 

<body>

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

    <div>

    <ul id="unord" class="clsUL"> 

        <li>Client-Side Languages

            <ul>

                <li>

                    jQuery

                </li>

                <li>

                    JavaScript

                </li>

                <li>

                    JScript

                </li>

            </ul>

        </li>

        <li>Server-Side Languages

            <ul>

                <li>

                    C#

                </li>

                <li>

                    VB.NET

                </li>

                <li>

                    Others

                </li>

            </ul>

        </li>

    </ul>   

    </div>

    </form>

</body>

</html>



The code shown above, collapses and expands the section of <li> kept inside <ul>. Needless to say, jQuery rocks!

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

Ramesh said...

Very very helpful.Thanks.

Tim said...

By far the easiest to use i've seen. 1 question - how to collapse all at initial page load?

Anonymous said...

I'd also like to know how to collapse all on initial load.