Convert a single level dropdown to a multilevel level using jquery

advertisements

I just developed a single level dropdown menu using jquery... How to refactor the same code to make it a multilevel dropdown menu...

Here is my working sample....

The jquery what i used,

$(document).ready(function() {
$("#Programming ul.child").removeClass("child");
$("#Programming li").has("ul").hover(function() {
   $(this).addClass("current").children("ul").fadeIn();
     }, function() {
    $(this).removeClass("current").children("ul").stop(true, true).css("display",
                                                                     "none");
                              });
                            });
‚Äč

EDIT:

Menu1       Menu2
 SubMenu1    SubMenu1
 Submenu2    SubMenu2
    SubMenu21
    SubMenu22

The second submenu level can be anywere...


Here is my solution: http://jsbin.com/oteze/9 I tested it on Firefox 3.6.8. ADD: Now it works in IE7 too.

You can nest any number of submenus anywhere. Just like that:

<li><a href="#">Child 1.2</a>
   <ul class="child">
       <li><a href="#">Child 1.2.1</a></li>
       <li><a href="#">Child 1.2.2</a></li>
   </ul>
</li>

I modified your code a little, so there is difference between first level submenu and other levels. I also moved all show/hide logic to JS.

   $(document).ready(function() {

        $("#Programming ul.child-first-level").hide();
        $("#Programming ul.child").hide();

        $("#Programming ul.child").each(function(index) {
            $(this).css("margin-left", $(this).parent().css("width"));
        });

        $("#Programming li ul.child-first-level").parent().hover(
            function() {
                $(this).children("ul").fadeIn();
            },
            function() {
                $(this).children("ul").stop(true, true).css("display", "none");
            }
        );

        $("#Programming li ul.child").parent().hover(
            function() {
                var offset = $(this).children("ul").offset();
                offset.top = 0;
                $(this).children("ul").offset(offset);
                $(this).children("ul").css("margin-left", $(this).parent().css("width"));
                $(this).children("ul").fadeIn();
            },
            function() {
                $(this).children("ul").stop(true, true).css("display", "none");
            }
        );

   });