Alex
Alex

Reputation: 7067

Scrolling with animation

I need to execute the javascript method scrollTo(x, y) with animation. I cant' use jQuery to do it.

Upvotes: 5

Views: 1028

Answers (2)

gblazex
gblazex

Reputation: 50109

[Working demo]

function interpolate( source,target,pos ) { 
  return ( source + (target - source) * pos ); 
}

function easing( pos ) { 
    return ( -Math.cos( pos * Math.PI ) / 2 ) + 0.5; 
}

function scrollTop( duration ) {

  duration = duration || 1000;

  var startY = window.pageYOffset,
      start  = Number(new Date()),
      finish = start + duration;

  var interval = setInterval(function() {

    var now = Number(new Date()),
        pos = (now > finish) ? 1 : (now - start) / duration;

     scrollTo(0, interpolate( startY, 0, easing(pos) ));

     if ( now > finish )
       clearInterval( interval );
  }, 15);
};

Upvotes: 9

user335938
user335938

Reputation:

You can animate (almost) anything in Javascript by using the window.setTimeout() and window.clearTimeout() calls. See http://www.w3schools.com/js/js_timing.asp

Upvotes: 2

Related Questions