Search code examples
jquerymouseoutfadeto

Jquery Mouseout dropdown menu


Im trying to fix my mouseout event.

Ive got the element

<div id="dropdown"></div>

to show when Im hovering on it. But I want it to dissapear when theres a mouseout event on the ".page_item.page-item-2" element AND #dropdown element.

Here's my Jquery code (that dosen't fully work)

$(document).ready(function(){
$("#dropdown").css('display', 'none');
$(".page_item.page-item-2").hover(
            function() {
    $("#dropdown").fadeTo("fast", 1.0);

    });
    var s = $(".page_item.page-item-2").mouseout;
    var b = $("#dropdown").mouseout;
    if(s && b){
    $("#dropdown").fadeTo("fast", 0.0);
    }    
});

Im sure theres a simple solution to this. Please help


Solution

  • You could set a timeout in the mouseout event to fade out the element after some time. And reset the timeout everytime a mouseenter event occurs. Here is a full working minimal example.

    <div class="page_item page-item-2">Hello</div>
    <div id="dropdown">World</div>
    
    <script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
        $("#dropdown").css('display', 'none');
        function clear_timeout() {
            clearTimeout($("#dropdown").data('timeout'));
            $("#dropdown").fadeIn("fast");
        }
        function set_timeout() {
            var timeout = setTimeout(function(){
                $("#dropdown").fadeOut("fast");
                $("#dropdown").css('display', 'none');
            }, 100);
            $("#dropdown").data('timeout', timeout);
        }
        $(".page_item.page-item-2").mouseenter(clear_timeout);
        $("#dropdown").mouseenter(clear_timeout);
        $(".page_item.page-item-2").mouseout(set_timeout);
        $("#dropdown").mouseout(set_timeout);
        });
    </script>