compilingJohnny
compilingJohnny

Reputation: 107

scroll to top not animating smoothly

My code:

$('#scroll-image').click(function(){
    $(window).animate({scrollTop: 0}, 2000);
    return false;
});

When i click on #scroll-image the page does scroll up but it happens instantly. I want it to scroll smoothly. I looked around and other's use the same code and theirs works perfectly. Any thoughts?

Upvotes: 2

Views: 192

Answers (3)

Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Try this instead:

$("html, body").animate({ scrollTop: "0" }, 2000);

As in:

$('#scroll-image').on('click', function(){
                $("html, body").animate({scrollTop: 0}, 2000);
                return false;
        });
.box {
  
height: 1000px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>

<a id="scroll-image" href="#">Scroll to top</a>

The reason you animate html AND body is because different browsers respond to different elements -- by doing both it will be compatible with more browsers.

Upvotes: 2

Hunter Turner
Hunter Turner

Reputation: 6894

You're getting errors using $(window). Use $("html, body") instead.

$("html, body").animate({scrollTop: 0}, 2000);

Here is a fiddle.

Upvotes: 2

Andy
Andy

Reputation: 221

You want to animate the html and body elements, not the window.

$('#scroll-image').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 2000);
    return false;
});

Upvotes: 2

Related Questions