189

I set the page to scroll to top when a button is clicked. But first I used an if statement to see if the top of the page was not set to 0. Then if it's not 0 I animate the page to scroll to the top.

var body = $("body");
var top = body.scrollTop() // Get position of the body

if(top!=0)
{
  body.animate({scrollTop:0}, '500');
}

The tricky part now is animating something AFTER the page has scrolled to the top. So my next thought is, find out what the page position is. So I used console log to find out.

console.log(top);  // the result was 365

This gave me a result of 365, I'm guessing that is the position number I was at just before scrolling to the top.

My question is how do I set the position to be 0, so that I can add another animation that runs once the page is at 0?

Thanks!

Juan Di Diego
  • 1,893
  • 2
  • 12
  • 4
  • 1
    it is needed that those button on which you fire event always visible? If not then i have a code which not need any kind of condition which can be do easy for your first condition – The Mechanic May 10 '13 at 04:42
  • 1
    There should not be quotes around the milliseconds. The "string" the documentation refers to are the slow/fast – mplungjan May 04 '17 at 07:19

12 Answers12

339

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

For example:

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.

Also, the 'swing' is there to set the easing. Check out http://api.jquery.com/animate/ for more info.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
TLS
  • 3,585
  • 1
  • 19
  • 20
  • 1
    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"); }); } – Juan Di Diego May 10 '13 at 04:49
  • I had to mention animate duration without quotes when I had only 2 parameters for animate function. That was weird. – iMatoria Dec 09 '13 at 01:51
  • 5
    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"); }); – Andrew Jun 10 '14 at 21:54
  • 29
    Your callback will execute twice, by the way, because you selected two elements. – Big McLargeHuge Oct 31 '14 at 18:26
  • 8
    Thomas had good point adding body and html. Case 1. Chrome reading body and srolling, FIrefox need html to do it. – fearis Apr 02 '15 at 16:37
  • 4
    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. – Lev Lukomsky Jun 27 '16 at 20:23
  • @ThomasStiegler You same my day – Owaiz Yusufi Aug 08 '18 at 15:34
67

Try this code:

$('.Classname').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});
bjb568
  • 11,089
  • 11
  • 50
  • 71
Shailesh
  • 980
  • 8
  • 16
  • 8
    `$("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. – Mickäel A. Dec 13 '13 at 15:47
  • 11
    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. – commonpike Feb 09 '14 at 11:55
39

Use this:

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

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

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

});
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49
Beep
  • 2,737
  • 7
  • 36
  • 85
8

for this you can use callback method

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
The Mechanic
  • 2,301
  • 1
  • 26
  • 37
7

Try this instead:

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');
      });
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Kishan Patel
  • 1,358
  • 10
  • 24
7

Simple solution:

scrolling to any element by ID or NAME:

SmoothScrollTo("#elementId", 1000);

code:

function SmoothScrollTo(id_or_Name, timelength){
    var timelength = timelength || 1000;
    $('html, body').animate({
        scrollTop: $(id_or_Name).offset().top-70
    }, timelength, function(){
        window.location.hash = id_or_Name;
    });
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • '**timelength**' is already passed-in as a parameter so no need to declare it with 'var'. An 'edit' of this answer was not possible, as it was less than 6 characters! ;-) +1 – Anthony Walsh May 31 '19 at 04:11
  • @AnthonyWalsh no way afaik. `var` is needed not to overwrite the global one (if there exist global variable with that name) – T.Todua Jun 01 '19 at 12:35
  • Fair enough ;-) I am using _TypeScript_ and passing in a number directly as a parameter for _timelength_ so all local scope in my case. Cheers! – Anthony Walsh Jun 03 '19 at 04:29
4

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Scorby
  • 41
  • 1
4
jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");
    });
Junaid
  • 4,682
  • 1
  • 34
  • 40
1

you can use both CSS class or HTML id, for keeping it symmetric I always use CSS class for example

<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a> 
|
|
|
<section class="section-plans js--section-plans clearfix">

$(document).ready(function () {
    $('.js--scroll-to-plans').click(function () {
        $('body,html').animate({
            scrollTop: $('.js--section-plans').offset().top
        }, 1000);
        return false;})
});
Rafiq
  • 8,987
  • 4
  • 35
  • 35
0

you must see this

$(function () {
        $('a[href*="#"]:not([href="#"])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });

or try them

$(function () {$('a').click(function () {
$('body,html').animate({
    scrollTop: 0
}, 600);
return false;});});
0
$("body").stop().animate({
        scrollTop: 0
    }, 500, 'swing', function () {
        console.log(confirm('Like This'))
    }
);
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
0

Hello everyone I was facing a similar issue and this worked fine for me:

jQuery(document).on('click', 'element', function() {
  let posTop = jQuery(target).offset().top;
  console.log(posTop);
  $('html, body').animate({scrollTop: posTop}, 1, function() {
    posTop = jQuery(target).offset().top;

    $('html, body').animate({scrollTop: posTop}, 'slow');
  });
});
Sean Kumar
  • 26
  • 4