Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery-animate() can't stop?

I have a button used to scroll back to the top of the page when clicked. I want to have an animation effect.

$("#back-to-top").click(function() {
        $(document.body).animate({scrollTop: 0}, 800);
        return false;
    });

When I click on the button, it did scroll back to top. However, I can't scroll down and it seemed when I scroll down the function is called. When I use

            $(document).scrollTop(0);

it works well. What's the problem? Here's my Fiddle I'm new to Fiddle, it just didn't work!

like image 280
jinglei Avatar asked Jan 28 '26 10:01

jinglei


2 Answers

Try like this

$("#back-to-top").click(function(e) {
  e.preventDefault();
  $("body, html").animate({scrollTop: 0}, 800);
});

Update
According to your fiddle, you have to put this function outside of $(window).scroll( function() {});

like image 141
smdsgn Avatar answered Jan 31 '26 00:01

smdsgn


Your problem is actually browser based, I tested this in Firefox which it didn't work. I then tested it in Chrome and it worked fine. Try using $('html, body').animate({scrollTop:0},500); instead.

like image 34
Kieron606 Avatar answered Jan 30 '26 23:01

Kieron606