Center a Bootstrap drop-down select scroll bar to the selected item

drop-down-menu, html, javascript, jquery, twitter-bootstrap

Solution

Not only is it possible, it's actually much easier to deal with native HTML objects than it is to deal with the mysteries and inconsistencies of styling the `<select>` element.

You just have to listen to the dropdown open event with `shown.bs.dropdown`. Once it's open, just find the only `.active` item and call `.focus()` to bring it into view.

Like This:

$(".dropdown").on("shown.bs.dropdown", function() {
   $(this).find(".dropdown-menu li.active a").focus()
});

Demo in Stack Snippets:

$(".dropdown.focus-active").on("shown.bs.dropdown", function() {
   $(this).find(".dropdown-menu li.active a").focus()
});
.scrollable-menu {
    height: auto;
    max-height: 200px;
    overflow-x: hidden;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>

<div class="container" >

  <div class="dropdown focus-active">
    <a href="#" class="btn btn-primary"
       data-target="#"  data-toggle="dropdown" 
       aria-haspopup="true" role="button" aria-expanded="false">
      Dropdown trigger
      <span class="caret"></span>
    </a>

    <ul class="dropdown-menu scrollable-menu" role="menu" aria-labelledby="dLabel">
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
      <li><a href="#">Item 3</a></li>
      <li><a href="#">Item 4</a></li>
      <li><a href="#">Item 5</a></li>
      <li><a href="#">Item 6</a></li>
      <li><a href="#">Item 7</a></li>
      <li><a href="#">Item 8</a></li>
      <li class="active"><a href="#">Item 9</a></li>
      <li><a href="#">Item 10</a></li>
      <li><a href="#">Item 11</a></li>
      <li><a href="#">Item 12</a></li>      
    </ul>
  </div>

</div>

Problem

Here's a question on how to center a `<select>` scroll bar to the selected item. I'd like to find a way to do the same thing for a Bootstrap Dropdown Menu so that the menu automatically scrolls to the `.active` list item. Here's some code: ``` <ul> <li class="dropdown switch"> <a href="active" class="dropdown-toggle" data-toggle="dropdown" id="switch-a"> <span>Name</span> </a> <ul class="dropdown-menu switch-items" id="switch-dd"> <li>...</li> <li>...</li> <li class="active active-dd"></li> . . . <li>...</li> </ul> </li> </ul> ``` Is this possible or do I have to a HTML `<select>` and spending time styling it?

Original source