Recently, I was working on creating a navbar with a dropdown menu that opens when hovered over. After some trial and error, I managed to achieve this functionality using the following jQuery code:
$('body').on('mouseenter mouseleave', '.dropdown', function (e) {
var dropdown = $(e.target).closest('.dropdown');
var menu = $('.dropdown-menu', dropdown);
dropdown.addClass('show');
menu.addClass('show');
setTimeout(function () {
dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
}, 300);
});
I also utilized the following CSS snippet to enhance the dropdown behavior:
.dropdown:hover>.dropdown-menu {
display: block;}
However, I encountered an issue on smaller devices, where clicking on the dropdown title would open the menu but not close it upon a subsequent click (similar to how Bootstrap 4 toggler functions in a standard scenario).
To address this challenge, I am seeking guidance on how to configure the dropdown feature to activate when hovering over the title on larger screens and switching to a click-based activation on smaller screens.
Below is a snippet of the HTML structure for reference:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
...