If mouse over for over 2 seconds then show else don't?
Asked Answered
P

2

33

Here is a jQuery slide function I have applied to a div on hover in order to slide a button down.

It works fine except that now everytime someone moves in and out of it, it keeps bobbing up and down.

I figured if I put a one or two second delay timer on it it would make more sense.

How would I modify the function to run the slide down only if the user is on the div for over a second or two?

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">

$("#NewsStrip").hover(
function () {
    $("#SeeAllEvents").slideDown('slow');    },
function () {
    $("#SeeAllEvents").slideUp('slow');
});

</script>
Poseidon answered 29/6, 2012 at 14:27 Comment(3)
Exact duplicate of jQuery - How to tell .hover() to wait?Husking
@T.J.Crowder if you read the question then the OP is not asking exactly that.Emboly
@ThomasClayson: Apparently they are. Same question, same accepted answer.Husking
S
70

You need to set a timer on mouseover and clear it either when the slide is activated or on mouseout, whichever occurs first:

var timeoutId;
$("#NewsStrip").hover(function() {
    if (!timeoutId) {
        timeoutId = window.setTimeout(function() {
            timeoutId = null; // EDIT: added this line
            $("#SeeAllEvents").slideDown('slow');
       }, 2000);
    }
},
function () {
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    else {
       $("#SeeAllEvents").slideUp('slow');
    }
});

See it in action.

Slickenside answered 29/6, 2012 at 14:34 Comment(5)
@xDazz Thanks jon and xDazz. The slide down works beautifully but it doesnt slide back up on mouse out? Am I missing or doing something wrong?Poseidon
Try getting rid of the if else blocks in the second function. You don't really need them. Calling those methods like that won't have any detrimental effect if you remove the if else. And its probably why its not sliding up again. :)Emboly
@ThomasClayson Well now it slides down and up just once and then goes inactive.WeirdPoseidon
@user1266515: Fixed a small bug and added a JSFiddle link. How does it look?Slickenside
@Slickenside thank you for sharing some creative power behind using a setTimeout. It helped me out too.Arun
P
4
var time_id;

$("#NewsStrip").hover(
function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideDown('slow');
    }, 2000);
}, function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideUp('slow');
    }, 2000);
});
Proxy answered 29/6, 2012 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.