Bootstrap Dropdown with Hover
OK, so what I need is fairly straightforward.
I have set up a navbar with some dropdown menus in it (using class="dropdown-toggle" data-toggle="dropdown"
), and it works fine.
The thing is it works "onClick
", while I would prefer if it worked "onHover
".
Is there any built-in way to do this?
Solution 1:
The easiest solution would be in CSS. Add something like...
.dropdown:hover .dropdown-menu {
display: block;
margin-top: 0; // remove the gap so it doesn't close
}
Working Fiddle
Solution 2:
The best way of doing it is to just trigger bootstraps click event with a hover. This way, it should still remain touch device friendly
$('.dropdown').hover(function(){
$('.dropdown-toggle', this).trigger('click');
});
Solution 3:
You can use jQuery's hover function.
You just need to add the class open
when the mouse enters and remove the class when the mouse leaves the dropdown.
Here's my code:
$(function(){
$('.dropdown').hover(function() {
$(this).addClass('open');
},
function() {
$(this).removeClass('open');
});
});
Solution 4:
An easy way, using jQuery, is this:
$(document).ready(function(){
$('ul.nav li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(200);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(200);
});
});