Rectangle 27 232

To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Where that alert code is, you can execute more javascript to add in further animation.

Thanks Thomas, that's what I needed. I also added a delay since the class is added so quickly. if(top!=0) { console.log("hidden scroll"); body.animate({scrollTop:0}, '500', 'swing', function() { console.log("Finished animating"); leftitems.delay(1000).removeClass("slide"); }); }

I'm not sure if it's because this post is 4 years old, but I think in newer versions of jQuery you need to remove those single quotes around the timing: body.animate({scrollTop:0}, 500, 'swing', function() { alert("Finished animating"); });

Your callback will execute twice, by the way, because you selected two elements.

Thomas had good point adding body and html. Case 1. Chrome reading body and srolling, FIrefox need html to do it.

Just tried $('html') does not work in Chrome and $('body') does not work in Firefox, so $('html, body') is needed. And also calling .stop() is a good thing I tried to call animate several times quickly in chrome and after that I could not scroll down the page.

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 227

To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Where that alert code is, you can execute more javascript to add in further animation.

Thanks Thomas, that's what I needed. I also added a delay since the class is added so quickly. if(top!=0) { console.log("hidden scroll"); body.animate({scrollTop:0}, '500', 'swing', function() { console.log("Finished animating"); leftitems.delay(1000).removeClass("slide"); }); }

I had to mention animate duration without quotes when I had only 2 parameters for animate function. That was weird.

I'm not sure if it's because this post is 4 years old, but I think in newer versions of jQuery you need to remove those single quotes around the timing: body.animate({scrollTop:0}, 500, 'swing', function() { alert("Finished animating"); });

Your callback will execute twice, by the way, because you selected two elements.

Thomas had good point adding body and html. Case 1. Chrome reading body and srolling, FIrefox need html to do it.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 118

<button onclick="scrollToTop(1000);"></button>
function scrollToTop(scrollDuration) {
    var scrollStep = -window.scrollY / (scrollDuration / 15),
        scrollInterval = setInterval(function(){
        if ( window.scrollY != 0 ) {
            window.scrollBy( 0, scrollStep );
        }
        else clearInterval(scrollInterval); 
    },15);
}

2# JavaScript (ease in and out):

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

Due to the high amount of up-voters, I rechecked my code I wrote a couple of years ago and tried to optimize it. Further more I added a little mathematical explanation at the bottom of my code.

UPDATE (ease in and out):

For a smoother slide/animation, done with the requestAnimationFrame method.

function scrollToTop(scrollDuration) {
    var cosParameter = window.scrollY / 2,
        scrollCount = 0,
        oldTimestamp = performance.now();
    function step (newTimestamp) {
        scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
        if (scrollCount >= Math.PI) window.scrollTo(0, 0);
        if (window.scrollY === 0) return;
        window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)));
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
    Explanations:
    - pi is the length/end point of the cosinus intervall (see above)
    - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
      (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
    - newTimestamp - oldTimestamp equals the duration

      a * cos (bx + c) + d                      | c translates along the x axis = 0
    = a * cos (bx) + d                          | d translates along the y axis = 1 -> only positive y values
    = a * cos (bx) + 1                          | a stretches along the y axis = cosParameter = window.scrollY / 2
    = cosParameter + cosParameter * (cos bx)    | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
    = cosParameter + cosParameter * (cos scrollCount * x)
*/

Keep in mind that const is not part of EcmaScript 5, but 6 with different semantics. Currently only Firefox and Chrome support it somehow. Read more here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/

Yes true, good object. So using var might be the better option untill all browsers are supporting const.

Can I see a JSFIDDLE of this in action? I can't seem to get it to work . . .

Thanks for this! I extended it a bit to allow scrolling to a specific element and a polyfill for browsers without performance.now() ... gist.github.com/joshcanhelp/a3a669df80898d4097a1e2c01dea52c1

javascript - scrollTop animation without jquery - Stack Overflow

javascript jquery html css
Rectangle 27 113

<button onclick="scrollToTop(1000);"></button>
function scrollToTop(scrollDuration) {
    var scrollStep = -window.scrollY / (scrollDuration / 15),
        scrollInterval = setInterval(function(){
        if ( window.scrollY != 0 ) {
            window.scrollBy( 0, scrollStep );
        }
        else clearInterval(scrollInterval); 
    },15);
}

2# JavaScript (ease in and out):

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

Due to the high amount of up-voters, I rechecked my code I wrote a couple of years ago and tried to optimize it. Further more I added a little mathematical explanation at the bottom of my code.

UPDATE (ease in and out):

For a smoother slide/animation, done with the requestAnimationFrame method.

function scrollToTop(scrollDuration) {
    var cosParameter = window.scrollY / 2,
        scrollCount = 0,
        oldTimestamp = performance.now();
    function step (newTimestamp) {
        scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
        if (scrollCount >= Math.PI) window.scrollTo(0, 0);
        if (window.scrollY === 0) return;
        window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)));
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
    Explanations:
    - pi is the length/end point of the cosinus intervall (see above)
    - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
      (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
    - newTimestamp - oldTimestamp equals the duration

      a * cos (bx + c) + d                      | c translates along the x axis = 0
    = a * cos (bx) + d                          | d translates along the y axis = 1 -> only positive y values
    = a * cos (bx) + 1                          | a stretches along the y axis = cosParameter = window.scrollY / 2
    = cosParameter + cosParameter * (cos bx)    | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
    = cosParameter + cosParameter * (cos scrollCount * x)
*/

Keep in mind that const is not part of EcmaScript 5, but 6 with different semantics. Currently only Firefox and Chrome support it somehow. Read more here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/

Yes true, good object. So using var might be the better option untill all browsers are supporting const.

Can I see a JSFIDDLE of this in action? I can't seem to get it to work . . .

Thanks for this! I extended it a bit to allow scrolling to a specific element and a polyfill for browsers without performance.now() ... gist.github.com/joshcanhelp/a3a669df80898d4097a1e2c01dea52c1

javascript - scrollTop animation without jquery - Stack Overflow

javascript jquery html css
Rectangle 27 32

$('.Classname').click(function(){
   $("html, body").animate({ scrollTop: 0 }, 600);
   return false;
});

$("html") should be used instead, because in your case if you add a callback function it will be called twice, once for html and once for body. And using body does nothing.

it seems that depends on the browser. in some, $('html') may do nothing, so you need to use both, and take care of the callback triggered twice.

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 31

$('.Classname').click(function(){
   $("html, body").animate({ scrollTop: 0 }, 600);
   return false;
});

$("html") should be used instead, because in your case if you add a callback function it will be called twice, once for html and once for body. And using body does nothing.

it seems that depends on the browser. in some, $('html') may do nothing, so you need to use both, and take care of the callback triggered twice.

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 16

$('a[href^="#"]').on('click', function(event) {

    var target = $( $(this).attr('href') );

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 500);
    }

});

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 16

$('a[href^="#"]').on('click', function(event) {

    var target = $( $(this).attr('href') );

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 500);
    }

});

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 6

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 6

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 55

Diode's solution didn't work for me - scroll() didn't differentiate between the animation and the user, meaning the animation stopped immediately. From a different post, the following works for me (modified for this purpose):

// Assign the HTML, Body as a variable...
var $viewport = $('html, body');

// Some event to trigger the scroll animation (with a nice ease - requires easing plugin )...
$('#element').click(function() {
    $viewport.animate({ 
        scrollTop: scrollTarget // set scrollTarget to your desired position
    }, 1700, "easeOutQuint");
});

// Stop the animation if the user scrolls. Defaults on .stop() should be fine
$viewport.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
         $viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); // This identifies the scroll as a user action, stops the animation, then unbinds the event straight after (optional)
    }
});

For touch screen devices you will need to add touchstart to your list of events, and check for it in the event itself ... || e.type == 'touchstart'

@Benjammin' - good tip, small nitpick - use === rather than ==

@OhadSchneider Yeah implicit conversion can bite you in the ass, but I don't think this situation has really any risk of a false positive. But yeah, go ahead and use the triple equals, probably better that way.

javascript - let user scrolling stop jquery animation of scrolltop? - ...

javascript jquery
Rectangle 27 4

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 4

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 2

Code with click function()

var body = $('html, body');

    $('.toTop').click(function(e){
        e.preventDefault();
        body.animate({scrollTop:0}, 500, 'swing');

});

.toTop = class of clicked element maybe img or a

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 2

Code with click function()

var body = $('html, body');

    $('.toTop').click(function(e){
        e.preventDefault();
        body.animate({scrollTop:0}, 500, 'swing');

});

.toTop = class of clicked element maybe img or a

jQuery .scrollTop(); + animation - Stack Overflow

jquery jquery-animate scrolltop
Rectangle 27 4

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Great answer! Glad you included the duration option. Just wanted to add that $("html, body").animate({scrollTop: 1024}, 5000); also works.

javascript - Is it possible to animate scrollTop with jQuery? - Stack ...

javascript jquery
Rectangle 27 4

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Great answer! Glad you included the duration option. Just wanted to add that $("html, body").animate({scrollTop: 1024}, 5000); also works.

javascript - Is it possible to animate scrollTop with jQuery? - Stack ...

javascript jquery
Rectangle 27 4

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Great answer! Glad you included the duration option. Just wanted to add that $("html, body").animate({scrollTop: 1024}, 5000); also works.

javascript - Is it possible to animate scrollTop with jQuery? - Stack ...

javascript jquery
Rectangle 27 4

You can use the jQuery animation for scroll page with a specific duration:

$("html, body").animate({scrollTop: "1024px"}, 5000);

where 1024px is the scroll offset and 5000 is the duration of animations in millisecond.

Great answer! Glad you included the duration option. Just wanted to add that $("html, body").animate({scrollTop: 1024}, 5000); also works.

javascript - Is it possible to animate scrollTop with jQuery? - Stack ...

javascript jquery
Rectangle 27 40

jQuery now supports scrollTop as an animation variable.

$("#id").animate({"scrollTop": $("#id").scrollTop() + 100});
$("#id").offset().top

javascript - How to scroll the window using JQuery $.scrollTo() functi...

javascript jquery scroll scrollto