Search code examples
jqueryhidedelaymouseleave

How can I remove a div with delay on mouseout/mouseleave?


I'm trying to make a function with delay. When I click on some paragraph, MENU is prepended to this paragraph. But I need to hide MENU when mouseleave or mouseout with delay.

Here's an example: http://jsfiddle.net/ynternet/bZLAv/

HTML

<p class="add_to_this1">Click here 1</p>
<p class="add_to_this2">Click here 2</p>
<p class="add_to_this3">Click here 3</p>

<div id="menu"> I'm here</div>

jQuery

jQuery.fn.handler = function () {
    $(this).on({
        click: function(e) {
            if ($(this).find("#menu").length) {
                return;
            }
            $('#menu').prependTo($(this));
            $("#menu").css({
                position: "absolute",
                left: "100px"
            }).show();
        }
    });
}
$(".add_to_this1").handler();
$(".add_to_this2").handler();
$(".add_to_this3").handler();

Solution

  • Here's a jsFiddle example

    jQuery.fn.handler = function () {
        $(this).on({
            click: function(e) {
                if ($(this).find("#menu").length) {
                    return;
                }
    
                $('#menu').prependTo($(this));
    
                $("#menu").css({
                    position: "absolute",
                    left: "100px"
                }).show();
            }
        });
    }
    $(".add_to_this1").handler();
    $(".add_to_this2").handler();
    $(".add_to_this3").handler();
    
    $('p[class^=add_to_this]').on('mouseleave', function(e) {
        setTimeout(function() {
            $('#menu').hide();
        }, 2000);        
    });