I am struggling to achieve the following functionality for my navbar dropdown menus:
- When the screen size is greater than 992px, I want the navbar dropdowns to open on mouse enter.
- For screens smaller than 992px, I want the dropdowns to open on click.
The problem I'm facing is that everything works correctly initially. However, after closing the dropdown by clicking its heading for a second time, I can no longer reopen it.
$(document).ready(function() {
function windowSizeCheck() {
var $windowSize = $(window).width();
if ($windowSize > 992) {
$('.dropdown').mouseenter(function() {
$(this).children('.dropdown .dropdown-menu').slideDown('slow');
$(this).children('.dropdown .dropdown-menu').toggleClass('open');
$(this).mouseleave(function() {
$(this).children('.dropdown .dropdown-menu').stop(true).slideUp('fast');
$(this).children('.dropdown .dropdown-menu').removeClass('open');
});
});
} else {
$('.dropdown').on('click', function() {
$(this).children('.dropdown .dropdown-menu').slideDown('slow');
$(this).children('.dropdown .dropdown-menu').toggleClass('open');
$(this).css({
'max-height': '400px',
'overflow-y': 'auto'
});
$(this).on('click', function() {
$(this).children('.dropdown .dropdown-menu').stop(true).slideUp('fast');
$(this).children('.dropdown .dropdown-menu').toggleClass('open');
});
});
}
}
windowSizeCheck();
});
.open {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
<nav class="navbar navbar-expand-lg navbar-light bg-white px-2 py-0 shadow-sm fixed-top">
<a href="#" class="navbar-brand">Brand Name</a>
<button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">
<span class="navbar-toggler-icon"></span>
</button>
<div id="navbarContent" class="collapse navbar-collapse">
<ul class="navbar-nav">
<!-- Dropdown menu items -->
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item"><a href="" class="nav-link text-uppercase"><i class="fas fa-shopping-cart"></i></a></li>
</ul>
</div>
</nav>