Mobile-compatible Dropdown Menu With jQuery And Nested Lists

Mobile-compatible Dropdown Menu With jQuery And Nested Lists
File Size: 4.38 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A responsive, semantic, mobile-friendly dropdown navigation that automatically switches between a horizontal list of menu links and a hamburger toggle menu depending on the current screen size.

Built with JavaScript (jQuery), CSS/CSS3 and nested HTML unordered lists.

See also:

How to use it:

1. Insert your menu list together with a hamburger toggle icon into a nav element.

<nav>
  <div>
    Place Any Hamburger Icon Here
  </div>
  <ul>
    <li><a href="#">jQueryScript.Net</a></li>
    <li>
      <a href="#">JavaScript</a>
      <ul>
        <li><a href="#">Angular</a></li>
        <li><a href="#">React</a></li>
        <li><a href="#">Vue</a></li>
      </ul>
    </li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

2. The required CSS for the horizontal dropdown menu when running on the desktop.

nav div {
  padding: 0.6em;
  background: #e3e3e3;
  display: none;
  cursor: pointer;
  color: #292929;
  font-size: 24px;
}

ul {
  margin: 0px;
  padding: 0px;
  background: #e3e3e3;
  list-style-type: none;
  position: relative;
}

ul li {
  display: inline-block;
}

ul li a {
  padding: 15px;
  color: #292929;
  text-decoration: none;
  display: block;
}

ul li:hover {
  background: lightgrey;
}

ul ul {
  position: absolute;
  min-width: auto;
  background: lightgrey;
  display: none;
}

ul ul li {
  display: block;
  background: #e3e3e3;
}

ul li:hover ul {
  display: block;
}

3. The required CSS for the hamburger toggle menu when running on the mobile (screen size < 769px).

@media (max-width: 768px) {
  nav div {
    display: block;
  }
  ul {
    display: none;
    position: static;
    background: #e3e3e3;
  }
  ul li {
    display: block;
  }
  ul ul {
    position: static;
    background: #e3e3e3;
  }
}

4. Load the necessary jQuery JavaScript library at the end of the document.

<script src="/path/to/jquery.min.js"></script>

5. The JavaScript to enable the dropdown navigation.

$("nav div").click(function(){
  $("ul").slideToggle();
  $("ul ul").css("display", "none");
});

$('ul li').click(function () {
  $(this).siblings().find('ul').slideUp();
  $(this).find('ul').slideToggle();
});

6. Re-init the dropdown navigation on window resize.

$(window).resize(function(){
  if($(window).width() > 768){
    $("ul").removeAttr('style');
  }
});

This awesome jQuery plugin is developed by murtazajafari. For more Advanced Usages, please check the demo page or visit the official website.