Search code examples
javascriptjqueryhtmlcssdrop-down-menu

Making a drop-down menu scrollable


I am trying to implement a drop down menu in a HTML page using CSS and jquery. Here is a sample of the HTML and javascript code.

<nav id="topNav">
  <ul>
    <li><a href="#" title="Nav Link 1">Menu 1</a></li>
    <li>
      <a href="#" title="Nav Link 2">Menu 2</a>
      <ul>
        <li><a href="#" title="Sub Nav Link 1">Sub Nav Link 1</a></li>
        <li><a href="#" title="Sub Nav Link 2">Sub Nav Link 2</a></li>
        <li><a href="#" title="Sub Nav Link 3">Sub Nav Link 3</a></li>
        <li><a href="#" title="Sub Nav Link 4">Sub Nav Link 4</a></li>
        <li class="last"><a href="#" title="Sub Nav Link 5">Sub Nav Link 5</a></li>
      </ul>
    </li>
    <li>
        <a href="#" title="Nav Link 3">Menu 3</a>
    </li>
  </ul>
</nav>

Here is the Javascript code:

var nav = $("#topNav");

//add indicators and hovers to submenu parents
nav.find("li").each(function() {
    if ($(this).find("ul").length > 0) {

        $("<span>").text("^").appendTo($(this).children(":first"));

        //show subnav on hover
        $(this).click(function() {
            $(this).find("ul").stop(true, true).slideToggle();
        });
    }
});

I will be adding content to menu programmatically, and I want the dropdown menus to be scrollable when the content of the dropdown menu gets too large.

How can I do this?


Solution

  • Try this using css like,

    #topNav ul li ul{
       max-height:250px;/* you can change as you need it */
       overflow:auto;/* to get scroll */
    }
    

    Demo