Skip to content Skip to sidebar Skip to footer

How To Animate An Object Depending On Page Scroll Position

I am currently using the following code to display/hide content based on the current scroll position: $(window).scroll(function () { if ($(window).scrollTop() >= 409) {

Solution 1:

Added .stop() to prevent animation fade errors and a boolean flag var io to prevent unnecessary animations:

jsBin demo

var $cc = $('.cliocont'),
    io  = false; // flag // compare booleans

$(window).scroll(function () {
  
   var is409 = $(window).scrollTop() >= 409; // booleanif (io != is409){
      io = is409;
      $cc.stop().fadeTo(800, is409?1.0:0.5);
   }
 
}); 

is409 ? 1.0 : 0.5 is a Conditional Operator and it's a shorthand for the if statement; boolean ? ifTrue : else ;

Solution 2:

I would say this is more proper, this includes the time locks for two animations -- do remove the console.log(...) calls:

<scripttype="text/javascript">var animateTrainer1 = true;
            var animateTrainer2 = true;
            $(window).scroll(function () {

                var scrollTop = $(window).scrollTop();

                if (scrollTop > 500 && animateTrainer1) {
                    animateTrainer1 = false;
                    console.log("animated trainer 1");
                    Animations.toPosition("#trainer1", 0, -100, 4000);
                }

                if (scrollTop > 800 && animateTrainer2) {
                    animateTrainer2 = false;
                    console.log("animated trainer 2");
                    Animations.toPosition("#trainer2", 100, 340, 4000);
                }

            });

        </script>

Post a Comment for "How To Animate An Object Depending On Page Scroll Position"