5

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

hpique
  • 119,096
  • 131
  • 338
  • 476
Alex
  • 6,957
  • 12
  • 42
  • 48

2 Answers2

9

[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);
};
gblazex
  • 49,155
  • 12
  • 98
  • 91
2

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