views:

127

answers:

2

I'm using the jQuery .scroll() function to make a certain element fade to 0.2 opacity. Since there is no native "scrollstop" indicator, I decided to make the element fade back to 1.0 opacity on hover. However, it doesn't work.

Here's my code:

$(document).ready(function() {  
$(window).scroll(function() {
    $("#navlist").animate({ opacity: 0.2 }, 2000);
});

$("#navlist").hover(    
    function() {
        $(this).animate({ opacity: 1 }, 500);
    }, function() {
        $(this).animate({ opacity: 1 }, 500); // just to be safe?
    }
);
});

When I scroll, the #navlist element fades, but when you hover over it nothing happens. But if you refresh the page when you're half way down, the element automatically fades as soon as you refresh, before I've scrolled, and if you try to hover to fade it back in, nothing happens.

Any thoughts?

A: 

The problem is that the scroll event, gets called multiple times during a single scroll (10-20 per a single mouse wheel scroll), so #navlist gets a lot of animate events of 2 seconds.

I am not exactly sure what's going on with jQuery, but when you hover it, even though the opacity: 1 animations run, they end up running the queued #navlist animations.

I solved the problem using a sort of flag, I bet you can find something more efficient.

$(document).ready(function(){
   var isAnimationBusy = false;
   $(window).scroll(function(){
      if(isAnimationBusy) return;
      isAnimationBusy = true;
      $("#navlist").animate(
         { opacity: 0.2 }, 2000, 
         function(){ isAnimationBusy = false; }
      );
   });

   $("#navlist").hover(
      function(){
        isAnimationBusy = false;
         $(this).stop().animate({ opacity: 1 }, 500);
      },
      function(){
         isAnimationBusy = false;
         $(this).stop().animate({ opacity: 1 }, 500);
      }
   );
});

Edit: The animation stop will solve the problem, I still believe you should control how many times you call the animate event. There could be a performance hit.

UberNeet
You both were right with the .stop() call. I used this flag too because I think you're right about performance with calling scroll constantly. Thanks.
Jason Rhodes
+1  A: 

try to stop animation first

$(document).ready(function() {  
$(window).scroll(function() {
    $("#navlist").stop().animate({ opacity: 0.2 }, 2000);

});
$("#navlist").hover(function() {
    $("#navlist").stop().animate({ opacity: 1.0 }, 500);
},
function() {
    $("#navlist").stop().animate({ opacity: 1.0 }, 500);
}
);
Reigel