Last Updated: February 25, 2016
·
4.784K
· khay

jQuery Toggle

Simply create a toggle navigation menu with jQuery.

HTML Structure

<ul id="nav" class="dropdown">
    <li><a href="#">Link 1</a></li>
    <li><a class="link" href="#">Link 2</a>
        <ul class="second">
            <li>Item One</li>
            <li>Item Two</li>
            <li>Item Three</li>
        </ul>
   </li>
   <li><a href="#">Link 3</a></li>
</ul>

Script

$(document).ready(function(){   

    $('ul#nav').each(function() {
        var $dropdown = $(this);

        $("a.link", $dropdown).click(function(e) {
            e.preventDefault();
            $("a.link").addClass('active');
            $("ul.second", $dropdown).toggle();
            return false;
        });
    });

    $('html').click(function(){
        $("ul.second").hide();
        $("a.link").removeClass('active');
    });

});