Mobile Navigation Dropdown

Hi Guys,

Currently, I’m working on a mobile navigation. here is what I have so far: http://jsfiddle.net/JeremyEnglert/9cK3X/2/

As you can see, the parent links are highlighted in blue while the child links are highlighted in grey.

I would like to make it so only the parent links show until a parent link is clicked - in which case the child elements will then show. However, I would like the child elements to show without the page having to reload.

I’m assuming I will have to use some jQuery to make this happen - which I have very little experience with.

Anyone want to get me pointed in the right direction?

Your menu is nice and simple, so making the menu work is simply a matter of hiding the child menus and showing them after a parent is clicked, we can then mark the parent as active and then the child menu will be shown.

You’ll just need a little bit of CSS:


#main-nav_responsive .sub-menu { /* Hide by default */
    display:none;
}

#main-nav_responsive .active > .sub-menu { /* Show when the parent <li> is marked active */
    display:block;
}

And a few lines of jQuery


$(document).ready(function() {

    var $mainNav = $("#main-nav_responsive");

    $mainNav.on("click touchend", ".menu > li > a", function(e) { //touchend is faster on mobile devices
        var $li = $(this).closest("li");

        if ($li.find(".sub-menu").length > 0) { //only do toggling when an item with a submenu is tapped

            e.preventDefault(); //prevent the URL from being followed if this is a parent item's link

            $mainNav.find(".active").removeClass("active"); //if you want to allow all menus to be open, comment this line out

            $li.toggleClass("active");

        }

    });

});

On a sidenote, if you’re building a mobile site/app it might be worth looking in to using ZeptoJS it’s a lightweight library that has a jQuery compatible API. (Unless you end up doing really complicated things or you need Internet Explorer support).

I’ve also tweaked your Fiddle so you have a working example to go by http://jsfiddle.net/GeekyJohn/9cK3X/13/

Set second level ul to be invisible by default and create class to show the element.


li ul {
    display: none;
}

.show {
    display:block;
}

And to first level anchor elements bind jquery click event, that toggles visibility for subsequent ul element. The jquery selector might need adjusting, but the idea should be clear. Also not to reload page use event.preventDefault() in click handler.


$(function() {
    $("div>ul>li>a")&#8203;.click(function(event) {
        event.preventDefault();
        &#8203;$(this).next("ul").toggleClass("show");
    });&#8203;
});