jQuery

How to create simple tree structure menu using jquery and css


Hey Everyone! It’s been long since I wrote any tutorial but I hope you must be enjoying the freebies at this site.

This week I have a simple solution yet to another complicated problem. It’s the tree structure menu and here are its features. And thanks to Mr. Vivek for his solution.

Features:

  1. Multiple branches or sub menus.
  2. Dynamic change of arrows on toggle of the menu items.
  3. Simple css for easy understanding.
  4. Ultra slim Jquery.
  5. Sliding animation for the sub menus.

Now that you know its features here is where you can download them from. You are free to use it anywhere.

Update

Mr. Kaartikeyan R and Mr. Fast have raised an interesting challenge in the comments section. They have asked that ‘Can only one Menu Item be expanded at all times while the other collapse automatically?’ Yes it is totally possible with just a small tweak in the class and jquery. You can check the demo for this solution and download it below.

← Download Zip Test Drive →

Tutorial

Now for the learning part, like always I’ll give you a whole break up on how I did it.

HTML Part

First we will get out HTML ready. Create a main un-ordered list with ID ‘treeMenu’. Inside this ul tag we have the first level menu items inside each li tag. If you would like to have the second level sub items then within one li tag create another ul tag and place the sub items inside it. Now for that li tag add a class called ‘contentContainer’. This is for our reference so that we know whichever li tag with class ‘contentContainer’ will have a ul item nested inside which will have second level items. And we set display none to all the second level and third level ul items. Because we don’t want to see them in the first go. They should slide down only on clicking their parent li tag.


Note: Do not forget to include JScript.js file in the header. We add this for the jquery code to work in the later part. It is the normal jquery code that you get from www.jquery.com

To be more clear here is the code.

<ul id="treeMenu">
 
    <li class="contentContainer" id="TamilNadu">Tamilnadu
   
        <ul style="display: none">
           
            <li class="contentContainer">Trichy
               
                <ul style="display: none" >
                   
                    <li>BHEL</li>
                   
                    <li class="contentContainer">Thiruverumbur
                   
                        <ul style="display: none">
                            <li>BagavathiPuram</li>
                            <li>VOC Nagar</li>
                        </ul>
                       
                    </li>
                   
                    <li>Thillai Nagar</li>
                   
                </ul>
               
            </li> <!-- END TRICHY -->
           
            <li>Selam</li>
            <li>Chennai</li>
            <li>Madurai</li>
           
        </ul>
       
    </li> <!-- END TAMIL NADU -->
   
    <li class="main">Bangalore</li>
   
    <li class="main">Orissa</li>
   
    <li class="contentContainer">Kerela
   
        <ul style="display:none">
            <li>Mangalore</li>
            <li>Calicut</li>
            <li>Cochin</li>
        </ul>
       
    </li><!-- END KERALA -->
   
    <li class="main">Andhra</li>
   
</ul> <!-- END TREE MENU -->

Now for the Jquery part

As we all know jquery is the simplified form of javascript and it has some great functions. One such function is ‘toggle()’. This function gives out a even with every click. For eg: if the first click gives out ‘A’ event, the second click gives ‘B’ event and so on. Now these events can be got with the use of multiple ‘function()’ separated by a comma. Each function() will output a event. Here how it goes in simple terms.

$("#id").toggle(           
         
         function() { // START FIRST CLICK FUNCTION
            // WRITE ANY ACTION HERE
          }, // END FIRST CLICK FUNCTION

          function() { // START SECOND CLICK FUNCTION
            // WRITE ANY ACTION HERE
          }, // END SECOND CLICK FUNCTION
         
          …
          …
          …

         function() { // START LAST CLICK FUNCTION
            // WRITE ANY ACTION HERE
         } // END LAST CLICK FUNCTION

); // END TOGGLE FUNCTION

After the last click function if still the #id is clicked then it start looping to the first click function. This is how a toggle() function works. Now that we understood this lets look into our code and see how it has helped us.

First we get ul tag through its id and target all its li tags.

$("#treeMenu li").toggle();

Now the first function() meant for the first click does the following magic.

  1. On click on the li it finds its child ul and slide it down. We will be using the slideDown() function for this magic. It animates the sub menu to slide down and appear.
  2. Then we check if that li which was clicked hasClass ‘contentContainer’. We will be using hasClass() function for this magic. By default in css we will add a right arrow icon to the ‘contentContainer’ class.
  3. So if the hasClass() turns out to be positive then we replace ‘contentContainer’ class with ‘contentViewing’ class. Now the ‘contentViewing’ class has a down arrow added to it through css.
  4. And this is how we change the arrows in response to the closing and opening of the menus.
  5. Now for the closing of the menus we will be using Second click function(). Because the first function() is used for the first click, automatically the second click calls for the second function().
  6. Again here will check up if the li has a ul as its child and slide it up. We will be using slideUp() function for this magic. It animates the menu to move up and disappear.
  7. Also we would replace the ‘contentViewing’ class with ‘contentContainer’ class. So that the arrow changes automatically back to closed mode.

Here is the full jquery code.

<script type="text/javascript">
        $(document).ready(function() {
       
        //Class 'contentContainer' refers to 'li' that has child with it.
        //By default the child ul of 'contentContainer' will be set to 'display:none'
       
            $("#treeMenu li").toggle(          
           
                  function() { // START FIRST CLICK FUNCTION
                      $(this).children('ul').slideDown()
                      if ($(this).hasClass('contentContainer')) {  
                          $(this).removeClass('contentContainer').addClass('contentViewing');
                      }
                  }, // END FIRST CLICK FUNCTION
                 
                  function() { // START SECOND CLICK FUNCTION
                      $(this).children('ul').slideUp()

                      if ($(this).hasClass('contentViewing')) {
                          $(this).removeClass('contentViewing').addClass('contentContainer');
                      }
                        } // END SECOND CLICK FUNCTIOn
                    ); // END TOGGLE FUNCTION
                   
        }); // END DOCUMENT READY

     
    </script>

Now for the beautiful CSS

Just a few padding and margins to keep them appealing. Do not miss to note the arrow images I have given in the CSS.

/* START TREE MENU */
#treeMenu li {
    border-left: 1px solid #FF7300;
    padding:0 0 10px 10px;
    color:#FFFC00;
}

#treeMenu li.contentContainer  {
    background:url('right.png ') no-repeat -3px 6px;
    color: #FFFFFF;
    cursor: pointer;
}

#treeMenu li.contentViewing {
        background:url('down.png ') no-repeat -4px 6px;
        color: #FFFFFF;
}

.contentContainer ul, .contentViewing ul {
    color:#FFFC00;
    margin:15px 0 0 10px;
}
/* END TREE MENU */

And that is it my friend. It is done. I hope you understood this magic. Do let me know through comments if you have any doubts and I’ll be glad to clear it out.

Latest Comments

26 responses to “How to create simple tree structure menu using jquery and css”

  1. Bijay says:

    The a href HTML attribute isn’t working inside the nested li, can you help me with that?

    • me_jcrp says:

      If you see in the DOM structure I haven’t included anchor tag for the items without nested li. You can simple add and anchor tag and it will work. If you still have a doubt do share your code with us and we will help.

  2. nikhil says:

    Hi href is not working,
    I am new and I dont know about DOM,

    My code is

    LeftMenu

    $(document).ready(function() {

    //Class ‘contentContainer’ refers to ‘li’ that has child with it.
    //By default the child ul of ‘contentContainer’ will be set to ‘display:none’

    $(“#treeMenu li”).toggle(

    function() { // START FIRST CLICK FUNCTION
    $(this).children(‘ul’).slideDown()
    if ($(this).hasClass(‘contentContainer’)) {
    $(this).removeClass(‘contentContainer’).addClass(‘contentViewing’);
    }
    }, // END FIRST CLICK FUNCTION

    function() { // START SECOND CLICK FUNCTION
    $(this).children(‘ul’).slideUp()

    if ($(this).hasClass(‘contentViewing’)) {
    $(this).removeClass(‘contentViewing’).addClass(‘contentContainer’);
    }
    } // END SECOND CLICK FUNCTIOn
    ); // END TOGGLE FUNCTION

    }); // END DOCUMENT READY

    MASTERS

    Regions

    Zone
    Division
    Branch

    Agencies
    Doctor
    Plan
    Location
    CompanyGl Codes

    SERVICING

    Party Management

    Parties
    Members

    Policy Management

    Policies
    Premium Deposit

    Commission Management

    Commission Received
    Bonus Commission
    Deduction on Commission

  3. nikhil says:

    HI the anchor tag is not working,

    And I had written tag in body but still it is not working,
    Kindly help

  4. nikhil says:

    I dont have a website..

  5. nikhil says:

    here is the link,

    http://jsfiddle.net/HSj9u/3/

    But output is not proper

  6. nikhil says:

    Ok…

    Will wait for your Reply,
    Thanks… 🙂

  7. nikhil says:

    Ok,
    Will Wait for your Reply…
    Thanks In Advance … 🙂

  8. nikhil says:

    Added $(” “).live(‘click’,(function() { preventDefault(); }); The page is Opening But now My UL Tags are not working

  9. nikhil says:

    hey u der????
    did u get the solution.

  10. Rider says:

    Awesome! Thank you! As simple as possible!

  11. thyro says:

    I have the same problem too. how to make url link work in each menu?

    Thanks

  12. hatline says:

    Nice example but you haven’t come out with your answer yet… please make somehow for the a to work within the li.

  13. bataka says:

    a href is not working. how to solve this problem

  14. tofayel says:

    I am a newbie.
    this is may code:
    <A href="index.php/admin_page_con/header_footer_setup” target=”admin_content”>slide 2.

    here the anchor tag not working. Actually i need target attributes.

    regards

  15. anil says:

    I want to thank first for this nice tutorial, can we use by animating it or giving som cool effect in tree structure.

  16. anil says:

    thanks for this tutorial. can we animate this tree by using and use in oroject.

  17. AAYUSHI says:

    please tell the solution for href tags to work with all nested li.
    Waiting for your reply

Leave a Reply

comment on this article