Valbone Valbone - 1 month ago 26
CSS Question

Hide dropdown div with jQuery on mouseout

I know there are hundreds of topics regarding this, however none of them seemed to work for me. I want for the dropdown to hide when the mouse leaves the element with jQuery, this is what I currently get:

Example of current undesired behavior

CodePen example.

jquery:

$(document).ready(function() {
$('.expand').click(function(e) {
e.preventDefault();
$('section').slideUp('normal');
if ($(this).next().is(':hidden') === true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
}
});
$('section').hide();
});

$('section').mouseleave(function(){
$(this).hide();
});


I've also tried the following:

$('section').hide();
$('.section').on('mouseout',function(){
$(this).hide();
})


Yet, nothing really seems to work correctly and gives me the same result. How can I fix this?

Answer

Working example.

You should use setTimeout()/clearTimeout() functions to solve your problem so you've to attach mouseleave event to the button with class dropbtn and both mouseleave/mouseleave events (using hover()) to the div dropdown-content so when the mouse leave the button to any other element you should check if the mouseenter is inside the dropdown, if yes clear the timeout the hide_dropdown so it will not hide the div, else your time out will hide the dropdown after 50ms :

var hide_dropdown;

$('.dropbtn').mouseleave(function(e){
    var _this = $(this);
    hide_dropdown = setTimeout(function(){
        _this.next('.dropdown-content').removeClass('show');   
    },50);
});

$('.dropdown-content').hover(
    function(){
        clearTimeout(hide_dropdown);
    },
    function(){
        $(this).removeClass('show');
    }
);

Hope this helps.