user3704659
user3704659

Reputation:

JavaScript issue: setTimeout

I'm trying to make a moving panel using JavaScript and jQuery.

I made this Working Demo, the JS part look like this:

$("nav.nav").hover(function(){
    $("nav.nav").animate({left:'-5px'},100,"swing");
  },
  function(){
    $("nav.nav").animate({left:'-170px'},100,"swing");
  });

As you can see, it's working, but I want to add a delay when I leave the panel because, some time, I leave the panel for 1 pixel by mistake and it's annoying.

I tried to use setTimeout("javascript function", milliseconds); like so:

$("nav.nav").hover(function(){
    $("nav.nav").animate({left:'-5px'},100,"swing");
  }, setTimeout(function(){
      $("nav.nav").animate({left:'-170px'},100,"swing");
  },10));

(The callback function in the timeout) but it's not working, and I have no idea why.

Upvotes: 0

Views: 128

Answers (2)

jfriend00
jfriend00

Reputation: 707178

I'd recommend using jQuery's .delay() (combined with .stop(true)) which handles the timer stuff for you automatically:

$("nav.nav").hover(function () {
    $("nav.nav").stop(true).animate({left: '-5px'}, 100, "swing");
},function () {
    $("nav.nav").stop(true).delay(1000).animate({left: '-170px'}, 100, "swing");
});

Working demo: http://jsfiddle.net/jfriend00/LuNHR/

Upvotes: 4

Anton
Anton

Reputation: 32581

You need to use the function inside the hover out function like this

var tOut = null;
$("nav.nav").hover(function () {
    clearTimeout(tOut); //Clear timout so it doesn't animate back when hovering
    $("nav.nav").animate({
        left: '-5px'
    }, 100, "swing");
},function () {
    tOut = setTimeout(function () {
        $("nav.nav").animate({
            left: '-170px'
        }, 100, "swing");
    }, 1000);
});

DEMO

Upvotes: 7

Related Questions