Can I delay The mouse-out function when using Jquery .hover()?
Asked Answered
G

2

6

I have a Text Box that is hidden until a div is hovered over. I am Using Jquery's hover function, and it works. But what I would like is to delay the mouse-out function for a few seconds before toggling closed. Here is my code.

// Pops out TxtBox in Left Column When Hovered then collapses after delay
$(".CollapsedLeft .LeftColumn .SearchHoverCatcher").hover(function() {
    $(".CollapsedLeft .LeftColumn .SearchHoverCatcher").addClass("Hovered");
}, function() {
$(".CollapsedLeft .LeftColumn .SearchHoverCatcher").delay(1000).removeClass("Hovered");
});

The above code Hides and shows the text box as desired but the 1000ms delay doesn't occur. Any Thoughts would be greatly appreciated.

Jquery Answers Please.

Gusher answered 30/10, 2013 at 21:59 Comment(0)
T
16

delay() works with animations, not just arbitrary statements. You can use a setTimeout:

http://jsfiddle.net/p4b7P/

var hoverTimeout;
$('#theDiv').hover(function() {
    clearTimeout(hoverTimeout);
    $(this).addClass('hovered');
}, function() {
    var $self = $(this);
    hoverTimeout = setTimeout(function() {
        $self.removeClass('hovered');
    }, 1000);
});
Tailspin answered 30/10, 2013 at 22:6 Comment(0)
D
0

You can use setTimeout function

var timer;
var delay = 1000;

$('#element').hover(function() {
    // on mouse in, start a timeout

    timer = setTimeout(function() {
        // do your stuff here
    }, delay);
}, function() {
    // on mouse out, cancel the timer
    clearTimeout(timer);
});

like this change your code accordingly

Delk answered 30/10, 2013 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.