How to get Hover Dropdowns in Bootstrap 5 Navbars

Class Object Oriented PHP

With the release of Bootstrap 5, the developers had made a decision to not support hover dropdown. They claim it has something to do with user experience on touch devices… whatever. I don’t buy it. On phones and small tablets, you’ve got the mobile menu, so you’re good.

Anyway, since they didn’t support the hover action on dropdown in Bootstrap 5, you’ve got to code it yourself.

Luckily, you can just copy and paste the below bit of jQuery javascript and you should be good to go!


    // Hover Bootstrap 5 Navbar Dropdowns
    
    $('.dropdown').mouseover(function () {
        if($('.navbar-toggler').is(':hidden')) {
            $(this).addClass('show').attr('aria-expanded', 'true');
            $(this).find('.dropdown-menu').addClass('show');
        }
    }).mouseout(function () {
        if($('.navbar-toggler').is(':hidden')) {
            $(this).removeClass('show').attr('aria-expanded', 'false');
            $(this).find('.dropdown-menu').removeClass('show');
        }
    });

If this doesn’t work for you and you get an error about $ being undefined, then your jQuery is probably stored in jQuery instead of $. Just wrap the above code in…

(function($) {

...the above code goes here...

})(jQuery)

If you’re a WordPress theme developer, then I’m sure you know where to put this. Otherwise, you may be scratching your head about where to put it. In your case, I suggest using a plugin that will let you inject code snippets into your WordPress site. My favorite plugin for this is Code Snippets.

By the way, this works for any Bootstrap 5 front-end. It’s not limited to WordPress at all.

If you have any questions or comments, leave them for me down below. Thanks!

Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Oznog
Oznog
1 month ago

Hi,

You don’t buy it. Sometimes it’s the client who requires hover. I think Bootstrap should offer both. However, You also don’t buy the idea of doing without jquery ; – )

tx