jQuery Animate Not Working on Scrool

Can you please take a look at This Demo and let me know why the second part of targeting the scroll position is not working? what I want to do is targeting scrool postion between 450 to 600 and applying this animation

$(".box-caption").animate({ "top": "600px" },1000);

to the element

$(function() {
    $( window ).scroll(function(e) {
    var y =   $( window ).scrollTop();
      if (y >200  && y< 400){
       $(".box-caption").animate({ "top": "350px" },1000);
    }
       if (y >450  && y< 600){
       $(".box-caption").animate({ "top": "600px" },1000);
    }
    });
}); 

as you can see it is working on first animate but not working for second! can you please let me know why this is happening and how I can fix it? thanks

Answers


I believe the animation is being triggered too many times when the previous animation hasn't finished. Poor little guy is all confused! Give this a try (Demo):

$(function() {
  var is_top = false;
    $( window ).scroll(function(e) {
    var y =   $( window ).scrollTop(); 
      if (y >200  && y< 400 && !is_top){
        is_top = true;
        $(".box-caption").animate({ "top": "350px" },1000);
      } 
      if (y >450  && y< 600 && is_top){
        is_top = false;
        $(".box-caption").animate({ "top": "600px" },1000);
      } 
    });
}); 

Explanation of Problem:

Every time you scrolled into the first range, it'd add the animation to the queue. Because the scroll event is being called "a whole bunch per second" you end up with second after second after second of those "first" animations. Then when you scroll down into the second range, the same thing happens with the second animation, but now you have to wait for all the first animations to finish! Same with the second animations before it can do the first again. You can sit there and not scroll and just watch it bounce around every twenty seconds or so after briefly scrolling.

Solution:

Using a boolean we make sure that each animation can only be run once in an alternating order. As soon as the first one runs, it cannot run again until the second one runs. Then when the second one runs, it can't run again until the first one runs. Back and forth they go only being triggered once per scrolling range.


Need Your Help

Should developers fear updates to their workstation software / development stack?

windows linux osx maintenance

As I have discovered, many developers avoid any updating (automatic or manual), because they fear it might do changes to their machine they don't understand, and the software they are developing mi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.