0

Similar problems have been dealt with before but I believe mine's slightly different owing to the use of the bind() function. Anyhow...

$('.overlay').bind("mouseenter",function(){
  $(this).fadeTo('slow', 0);
}).bind("mouseleave",function(){                
  setTimeout(function() { 
    $(this).fadeTo('slow', 1);
  }, 2000);
});

I want to fade out the overlay on "mouseenter", but only fade it back in 2000ms after "mouseleave".

I have an additional question: When the .overlay div fades out, I need to be able to click on what's beneath it i.e. I need the div to disappear completely or move down the z-index stack. However, if I try adding this in, the script thinks the mouse has left the .overlay div, so the .overlay fades back in.

For the same reason I can't use fadeOut() and fadeIn().

strangerpixel
  • 798
  • 1
  • 11
  • 27

1 Answers1

2

When the timeout fires this won't be what you expect. You can create a closure like this:

            $('.overlay').bind("mouseenter",function(){
                    $(this).fadeTo('slow', 0);
                    }).bind("mouseleave",function(){
                    var $this = $(this);                               
                    setTimeout(function() { 
                            $this.fadeTo('slow', 1);
                            }, 2000);
            });
Greg
  • 316,276
  • 54
  • 369
  • 333
  • Two questions: does the '$' in `var $this = ...` have any significance? And what would `$(this)` be referring to in his original code that you got around here? – idrumgood Sep 17 '09 at 17:49
  • No, the `$` in `var $this` is just to make the variable look more jQueryish. The `$` character has no special meaning in javascript. And its only an alias for "jQuery" in jQuery. – Eric Sep 17 '09 at 18:02
  • works fine, thanks - I see now that the $(this) wrapped inside the setTimeout function refers to something different. – strangerpixel Sep 18 '09 at 13:27
  • OK I have an additional question: When the .overlay div fades out, I need to be able to click on what's beneath it i.e. I need the div to disappear completely or move down the z-index stack. However, if I try adding this in, the script thinks the mouse has left the .overlay div, so the .overlay fades back in. For the same reason I can't use fadeOut() and fadeIn(). – strangerpixel Sep 18 '09 at 13:49