19

Bootstrap button dropdown: http://twitter.github.com/bootstrap/components.html#buttonDropdowns

When i select a button dropdown, i would like to use keyboard up/down to navigate between menu items and press enter to select one, just like http://twitter.github.com/bootstrap/javascript.html#dropdowns

Any ideas?

Mike
  • 3,515
  • 10
  • 44
  • 67
  • 1
    This might be a starting point: http://stackoverflow.com/questions/1409214/keyboard-navigation-for-menu-using-jquery – nickhar Mar 30 '13 at 15:41

2 Answers2

22

Bootstrap has native support for keyboard navigation.

Just add role="menu" to your dropdown-menu

Here is an example, just save as .html and take a test

<html>
<head>
  <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="btn-group">
    <button class="btn btn-default">1</button>
    <button class="btn btn-default">2</button>
    <button class="btn btn-default">3</button>
  <div class="btn-group">
    <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">menu</button>
      <ul class="dropdown-menu" role="menu">
        <li> <a href="#">one</a> </li>
        <li> <a href="#">two</a> </li>
        <li> <a href="#">three</a> </li>
      </ul>
    </div>
  </div>
</body>
</html>

http://jsfiddle.net/damphat/WJS9p/

damphat
  • 18,246
  • 8
  • 45
  • 59
  • 6
    Keep in mind though, that whatever you give `role="menu"` needs to be able to receive focus. See http://stackoverflow.com/a/1600194/601386. Only elements that can receive focus can bind to keyboard events. – flu Dec 04 '14 at 17:56
9

Possible reasons that this may not work in some cases:

  • Because you use a <div> or a <span> for .dropdown-toggle. Make it a <button> and it will work. Strange enough, not even this kind of element works: span.btn.btn-default.
  • Make sure your <a> element inside each <li> have an attribute of href="#" or href="" or generally has the attribute defined.
  • Make sure you have the role="menu" on the .dropdown-menu element.
NoOne
  • 3,851
  • 1
  • 40
  • 47