jquery - Javascript DIV Movement on scroll -


nim creating animation moves div incrementally on scroll. i'm close don't think code efficient , don't know how adapt add more arguments. instance, hitting height on page move object right , stop moving down. below js , codepen can found at;

http://codepen.io/anon/pen/kxhwu - original

http://codepen.io/anon/pen/dlxqg - messing moving right

var lastscrolltop = 0; var boxposition = $('#box').position(); var row2position = $('#row2').position();  var distance = $('#row2').offset().top,     $window = $(window);  console.log(distance);  $window.scroll(function() {     if ( $window.scrolltop() >= distance - 400 ) {       var st = $(window).scrolltop();       console.log(st);        $('#box').css({top: 0 + st});        //code not working        if(st >= 270) {         var boxpos = $('#box').position();         console.log(boxpos.left);         $('#box').css({left: boxpos.left + st});       }        //     lastscrolltop = st;      } }); 

i'm looking box start scrolling does, when hits half of row 2 scroll right.

i hope have explained in easy way!

thanks

http://codepen.io/anon/pen/thwlq

here example of how it; you'll need tweak numbers make work plan.

var $window = $(window); var $box = $("#box");  $window.scroll(function() {     var scrolltop = $window.scrolltop();      if (scrolltop >= 250 && scrolltop < 400) {       $box.css({top: -250 + scrolltop});           } else if(scrolltop >= 400 && scrolltop < 600) {       $box.css({left: (50+(scrolltop-400)/2)+"%"})     } }); 

if project has numerous elements this, i'd recommend scrollmagic (http://janpaepke.github.io/scrollmagic/) library.

as far efficiency concerned i'd recommend following:

1) cache jquery selectors (note $box variable). otherwise, jquery have query dom on every scroll event.

2) cache scrolltop rather querying multiple times within event callback.

3) although left , top work, using transform: translate() property more efficient, on mobile devices. (https://developer.mozilla.org/en-us/docs/web/css/transform). however, on mobile devices, scroll events fire @ completion of scroll, not while page scrolling.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -