Max
Max

Reputation: 629

ScrollTo with animation

how can i add an easing/animation/slowly moving to this function? At the moment it just jumps. Now it should move to the "anchor" with an animation.

<script type='text/javascript'>
        setTimeout("window.scrollBy(0,270);",3000);
</script>

Upvotes: 17

Views: 53806

Answers (9)

zixiCat
zixiCat

Reputation: 1059

We can make it simpler by using the css property scroll-behavior

html {
  scroll-behavior: smooth;
}

Upvotes: 0

xnim
xnim

Reputation: 363

For anyone viewing this question in 2019: this can now be done natively by using

window.scrollBy({
    top: 0,
    left: 270,
    behavior: 'smooth'
});

This works in all major browsers except edge and safari. See https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy#Examples

Upvotes: 23

Lokesh Gamot
Lokesh Gamot

Reputation: 48

This will Work, Assume you need to Smooth-scrolls to the top of the page.

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

Upvotes: 4

Raslanove
Raslanove

Reputation: 689

Adapted from this answer:

function scrollBy(distance, duration) {

    var initialY = document.body.scrollTop;
    var y = initialY + distance;
    var baseY = (initialY + y) * 0.5;
    var difference = initialY - baseY;
    var startTime = performance.now();

    function step() {
        var normalizedTime = (performance.now() - startTime) / duration;
        if (normalizedTime > 1) normalizedTime = 1;

        window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
        if (normalizedTime < 1) window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

This should allow you to smoothly scroll by the specified distance.

Upvotes: 13

jtheman
jtheman

Reputation: 7491

Using jQuery makes this much easier, perhaps with the scrollto plugin. http://flesler.blogspot.se/2007/10/jqueryscrollto.html

Consider a solution such:

<script type='text/javascript' src='js/jquery.1.7.2.min.js'></script>
<script type='text/javascript' src='js/jquery.scrollTo-min.js'></script>
<script type='text/javascript' src='js/jquery.easing.1.3.js'></script><!-- only for other easings than swing or linear -->
<script type='text/javascript'>
$(document).ready(function(){
    setTimeout(function() {
    $('html,body').scrollTo( {top:'30%', left:'0px'}, 800, {easing:'easeInBounce'} );
}, 3000);
});
</script>

Of course you need to dl the scripts.

See http://jsfiddle.net/7bFAF/2/ for a working example

Upvotes: 0

shunryu111
shunryu111

Reputation: 6533

also possible with plain javascript using request animation frame..

// first add raf shim
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

// main function
function scrollToY(scrollTargetY, speed, easing) {
    // scrollTargetY: the target scrollY property of the window
    // speed: time in pixels per second
    // easing: easing equation to use

    var scrollY = window.scrollY,
        scrollTargetY = scrollTargetY || 0,
        speed = speed || 2000,
        easing = easing || 'easeOutSine',
        currentTime = 0;

    // min time .1, max time .8 seconds
    var time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8));

    // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
    var PI_D2 = Math.PI / 2,
        easingEquations = {
            easeOutSine: function (pos) {
                return Math.sin(pos * (Math.PI / 2));
            },
            easeInOutSine: function (pos) {
                return (-0.5 * (Math.cos(Math.PI * pos) - 1));
            },
            easeInOutQuint: function (pos) {
                if ((pos /= 0.5) < 1) {
                    return 0.5 * Math.pow(pos, 5);
                }
                return 0.5 * (Math.pow((pos - 2), 5) + 2);
            }
        };

    // add animation loop
    function tick() {
        currentTime += 1 / 60;

        var p = currentTime / time;
        var t = easingEquations[easing](p);

        if (p < 1) {
            requestAnimFrame(tick);

            window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
        } else {
            console.log('scroll done');
            window.scrollTo(0, scrollTargetY);
        }
    }

    // call it once to get started
    tick();
}

// scroll it!
scrollToY(0, 1500, 'easeInOutQuint');

Upvotes: 46

Max
Max

Reputation: 629

got it myself. because of wordpress and the jquery.noConflict Mode i hade to modify the code:

<script type="text/javascript">
        (function($){
        $(document).ready(function(){
            setTimeout(function() {
            $('body').scrollTo( '300px', 2500 );
        }, 3000);
        });
        }(jQuery));
</script>

thanks for everybody!!!

Upvotes: 2

piatek
piatek

Reputation: 376

Another example with jQuery, uses the easing plugin for some nice effects:

http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizontal-page-scrolling-with-jquery/

Upvotes: 2

MarcoK
MarcoK

Reputation: 6110

When using jQuery, you could easily use the .animate function.

Here's an example on how it should work.

Upvotes: 1

Related Questions