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>
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1266515
  • 796
  • 3
  • 15
  • 33

2 Answers2

69

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • @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? – user1266515 Jun 29 '12 at 14:53
  • 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. :) – Thomas Clayson Jun 29 '12 at 15:01
  • @ThomasClayson Well now it slides down and up just once and then goes inactive.Weird – user1266515 Jun 29 '12 at 15:24
  • @user1266515: Fixed a small bug and added a JSFiddle link. How does it look? – Jon Jun 29 '12 at 15:40
  • @Jon thank you for sharing some creative power behind using a setTimeout. It helped me out too. – klewis Apr 25 '14 at 20:52
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);
});
xdazz
  • 158,678
  • 38
  • 247
  • 274