Reputation: 593
How to make bootstrap4 dropdown menu selectable by keyboard?
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown show">
<a class="btn btn-secondary dropdown-toggle" href="https://example.com" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
Upvotes: 1
Views: 1087
Reputation: 11342
With tabindex="0"
you can now use key tab
then key space
to open the drop-down list, and use tab
to navigate through the list item.
Also, the order of your source reference was incorrect, check the code below
$(document).ready(function() {
$('.dropdown').keydown(function(e) {
switch (e.which) {
// user presses the "up arrow" key
case 38:
var focused = $(':focus');
if (focused.hasClass('dropdown-toggle') || focused.is(':first-child')) {
$('.dropdown').find('.dropdown-item').first().focus();
} else {
focused.prev().focus();
}
break;
// user presses the "down arrow" key
case 40:
var focused = $(':focus');
if (focused.hasClass('dropdown-toggle') || focused.is(':last-child')) {
$('.dropdown').find('.dropdown-item').first().focus();
} else {
focused.next().focus();
}
break;
}
});
});
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<div class="dropdown show">
<a class="btn btn-secondary dropdown-toggle" href="https://example.com" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown link
</a>
<div class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#" tabindex="0">Action</a>
<a class="dropdown-item" href="#" tabindex="0">Another action</a>
<a class="dropdown-item" href="#" tabindex="0">Something else here</a>
</div>
</div>
Upvotes: 1