Make Bootstrap 4 dropdowns appear on hover

Bootstrap is awesome. I seriously love it and always use it for project builds. And that’s either Bootstrap 3 or 4 – whatever the projects require, I’ll usually always go with BS. When it comes to dropdowns, especially so in navigation menus, I always prefer dropdown submenus to appear on hover. By default, this is achieved when you click the parent navigation item in Bootstrap. If you want the dropdown to appear on hover of the parent item, you can do this in 2 ways: one via CSS and one via Javascript. Here’s how.

Method 1 – CSS

.dropdown:hover>.dropdown-menu {
  display: block;
}

Method 2 – JS

(function () {
            var e = document.querySelectorAll(".navbar-nav .dropdown, .navbar-nav .dropright"),
                n = ["mouseenter"],
                a = ["mouseleave", "click"];
            [].forEach.call(e, function (t) {
                var o = t.querySelector(".dropdown-menu");
                n.forEach(function (e) {
                    t.addEventListener(e, function () {
                        !(function (e) {
                            window.innerWidth < 992 ||
                                (e.classList.add("showing"),
                                setTimeout(function () {
                                    e.classList.remove("showing"), e.classList.add("show");
                                }, 1));
                        })(o);
                    });
                }),
                    a.forEach(function (e) {
                        t.addEventListener(e, function (e) {
                            !(function (e, t) {
                                setTimeout(function () {
                                    window.innerWidth < 992 ||
                                        (t.classList.contains("show") &&
                                            (("click" === e.type && e.target.closest(".dropdown-menu form")) ||
                                                (t.classList.add("showing"),
                                                t.classList.remove("show"),
                                                setTimeout(function () {
                                                    t.classList.remove("showing");
                                                }, 200))));
                                }, 2);
                            })(e, o);
                        });
                    });
            });
        })()

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *