Bootstrap 5 dropdown is defined as
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
<li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
<li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
</ul>
</div>
https://jsfiddle.net/b6or2s5e/
If clicked in Action button, first menu item Action is not active (highlighted):
Pressing down arrow is required to activate it:
How to fix it so that opening dropdown highlights first item like in normal windows desktop application menus?
2
Answers
You can simply add the built in
active
class in bootstrap and it will give you a blue background. Just get the first link in the dropdown menu and addactive
to its classList.There are some caveats though when using Boot Strap. Overriding BS classes can often be challenging. With the
a
tags classes set todropdown-item
the background is set to ‘transparent’ by default, this can not be overridden with a class unless your class comes from a css style sheet with the same name and place under the BS CSS CDN. But inline style will override the background.Also if you want hover effects on the drop down menu items, you can use JS eventListeners to set inline styles as I have done with the code in the snippet.
If you only want the first item set –
If you want mouseover (hover) on the other links –
You could also define your own style for the first item using inline styles –
Here is an example using your other question with the underlined elements code mashed in to one snippet on JS Fiddle