Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add delay before .hide() w/jQuery

Tags:

jquery

I have a simple code that keeps an element visible while a mouse hovers over it and hides it once the mouse is out.:

$(".item").hover(
    function () {
        $(this).show();
    }, 
    function () {
        $(this).hide();
    }                       
);

I would like to add some delay before it hides, but adding $(this).delay(500).hide();does not seem to work...

like image 689
santa Avatar asked Nov 26 '25 11:11

santa


2 Answers

.hide() without any arguments doesn't use the effects queue (and won't have to wait for .delay()). Instead, you could use $(this).delay(500).hide(0);

like image 155
zkhr Avatar answered Nov 28 '25 02:11

zkhr


var my_timer;
$(".item").hover(
    function () {
        clearTimeout(my_timer);
        $(this).show();
    }, 
    function () {
        var $this = $(this);
        my_timer = setTimeout(function () {
            $this.hide();
        }, 500);
    }                       
);

Here is a demo: http://jsfiddle.net/e3cNK/1/

If you want to be able to re-show the element after it has been hidden then you want to change the opacity of the element rather than changing its display to none. This will keep the elements in the regular flow of the page so when the user mouse-overs the hidden element it can show again:

var my_timer;
$(".item").hover(
    function () {
        var $this = $(this);
        $this.text('Mouse-Over');
        clearTimeout(my_timer);
        $this.stop().fadeTo(250, 1);
    },
    function () {
        var $this = $(this);
        $this.text('Mouse-Out');
        my_timer = setTimeout(function () {
            $this.fadeTo(250, 0);
        }, 500);
    }                       
);

Here is a demo: http://jsfiddle.net/e3cNK/2/

like image 28
Jasper Avatar answered Nov 28 '25 02:11

Jasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!