Dropdown
An earlier lesson covered how to style a dropdown menu. This lesson covers the JS half — what actually opens and closes it, how to trigger one manually from your own code, and the keyboard behavior the plugin adds for free. We'll finish with a TrailMap example that opens a dropdown from a custom button using jQuery instead of the usual data attribute.
The Declarative Way: data-toggle="dropdown"
Most of the time, that's the entire JS requirement — one attribute on the toggle element:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
Sort By <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Distance</a></li>
<li><a href="#">Difficulty</a></li>
</ul>
</div>
The jQuery Method: Manual Triggering
Call .dropdown('toggle') on the toggle element to open or close its menu from your own
script — useful when a dropdown needs to open in response to something other than a direct click,
like another control on the page.
$('.dropdown-toggle').dropdown('toggle'); // open/close the menu manually
Built-In Keyboard Navigation
The plugin wires up keyboard support automatically — you don't write any of this yourself:
| Key | Behavior |
|---|---|
↓ / ↑ | Move focus down or up through the menu items |
Esc | Closes the open menu and returns focus to the toggle |
TrailMap Example: Opening a Dropdown from a Custom Button
Suppose TrailMap has a separate "Filters" icon button, outside the dropdown itself, that should open
the sort menu when clicked. Skip data-toggle on that icon and call the jQuery method
instead:
<!-- TrailMap: dropdown with no data-toggle on the real trigger -->
<button id="filterIconBtn" class="btn btn-default">
<i class="fa fa-filter"></i>
</button>
<div class="dropdown">
<button class="dropdown-toggle" id="sortDropdown" style="display:none"></button>
<ul class="dropdown-menu">
<li><a href="#">Distance</a></li>
<li><a href="#">Difficulty</a></li>
</ul>
</div>
<script>
$('#filterIconBtn').on('click', function() {
$('#sortDropdown').dropdown('toggle');
});
</script>
.dropdown('toggle') is called on the element carrying .dropdown-toggle and sitting inside a .dropdown wrapper — it doesn't care whether the click came from a real user click on that element or from a jQuery handler on something else entirely.