Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams 2019, to avoid “This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning” use my script stackoverflow.com/a/57641938/5781320 user5781320 Aug 24, 2019 at 22:34 Try this css html,body{ scroll-behavior: smooth} and some script for scroll top window.scrollTo(0,0) Aslam khan Dec 25, 2022 at 8:01

If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo() method -- passing in 0, 0 will scroll the page to the top left instantly.

window.scrollTo(xCoord, yCoord);

Parameters

  • xCoord is the pixel along the horizontal axis.
  • yCoord is the pixel along the vertical axis.
  • That was my point, if you don't need to animate smooth scrolling then you don't need to use jQuery. – SavoryBytes Mar 1, 2012 at 21:47 Funny as jeff's comment is honestly for people who just want things to work cross browser 95% of the time should just use jQuery. This is coming from someone who has to write a lot of pure javascript right now because we can't afford the overhead of a library slowing down ad code :( – Will Jun 10, 2013 at 17:10 This answer has nothing to do with the question. It would be fine if the question was: What script and methods should I use to scroll to the top of the page? Correct answer is here: stackoverflow.com/questions/4147112/… – skobaljic Feb 11, 2014 at 12:00

    If you do want smooth scrolling, try something like this:

    $("a[href='#top']").click(function() {
      $("html, body").animate({ scrollTop: 0 }, "slow");
      return false;
    

    That will take any <a> tag whose href="#top" and make it smooth scroll to the top.

    +1. I was just wondering how to do something like this and google lead me here. QUestion though, where is "scrollTop" function in the docs? I just looked but couldn't find it. – sqram Jul 18, 2009 at 1:55 This does not work correctly when using animate's complete callback, as it will run it twice. – David Morales Jul 22, 2012 at 11:41 "html" and "body" are both required for browser compatibility, i.e. Chrome v27 scrolls with just "body" and IE8 does not. IE8 scrolls with just "html" but Chrome v27 does not. – SushiGuy May 30, 2013 at 16:56 @jalchr Actually, window.pageYOffset would be the property of the window e̶l̶e̶m̶e̶n̶t̶ object. – Alex W Oct 8, 2013 at 18:40
    // this changes the scrolling behavior to "smooth"
    window.scrollTo({ top: 0, behavior: 'smooth' });
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

    You may still need to polyfill support for the ScrollOptions (for certain browsers): github.com/iamdustan/smoothscroll – jneuendorf Dec 5, 2018 at 8:57 Can someone test this on Safari or Internet Explorer and see if it's working fine? Thanks – Fabio Magarelli Mar 26, 2020 at 10:23 @FabioMagarelli Its working fine on Safari, not tested on IE. FYI to test it on safari open any page which has scroll and copy paste the above code in Developer Tools -> Console it will scroll to top verified ( Safari Version 13.0.5). – Ganesh Ghalame Mar 26, 2020 at 10:41 This is the best answer. We can use document.body.scrollHeight for the top value if one wants to scroll to the bottom. – Talha Imam Feb 7, 2022 at 13:27 this is the same: if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; } – Vasilii Suricov Mar 31, 2019 at 10:45

    You don't need jQuery to do this. A standard HTML tag will suffice...

    <div id="jump_to_me">
        blah blah blah
    <a target="#jump_to_me">Click Here To Destroy The World!</a>
                    This is not going to  work if you call another button by using getElementById in the middle of a page.
    – Jim O.
                    Sep 9, 2020 at 18:21
    

    All of these suggestions work great for various situations. For those who find this page through a search, one can also give this a try. JQuery, no plug-in, scroll to element.

    $('html, body').animate({
        scrollTop: $("#elementID").offset().top
    }, 2000);
    
    (function smoothscroll(){
        var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentScroll > 0) {
             window.requestAnimationFrame(smoothscroll);
             window.scrollTo (0,currentScroll - (currentScroll/5));
    })();
    $(function(){
       var scroll_pos=(0);          
       $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
    </script>
    

    Edit:

    $('html, body').animate({scrollTop:(scroll_pos)}, 2000);
    

    Another way scroll with top and left margin:

    window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });
                    You can't use a string for the duration in the animate function, instead you should use:   $('html, body').animate({scrollTop:(scroll_pos)}, 2000);
    – Kenny Alvizuris
                    Jun 19, 2018 at 14:48
    

    Really strange: This question is active for five years now and there is still no vanilla JavaScript answer to animate the scrolling… So here you go:

    var scrollToTop = window.setInterval(function() {
        var pos = window.pageYOffset;
        if ( pos > 0 ) {
            window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
        } else {
            window.clearInterval( scrollToTop );
    }, 16); // how fast to scroll (this equals roughly 60 fps)
    

    If you like, you can wrap this in a function and call that via the onclick attribute. Check this jsfiddle

    Note: This is a very basic solution and maybe not the most performant one. A very elaborated example can be found here: https://github.com/cferdinandi/smooth-scroll

    Best solution for me. No plugins, no bulky jquery library just straightforward javascript. Kudos – user2840467 Nov 8, 2016 at 22:06 Man, I also created this same logic XD after 5 years, exactly the same logic, only values are different like, the interval time and that integer which we are using to subtract, can't believe XD. TBH, came here to answer but it's already there so upvoted your answer. – Germa Vinsmoke Jul 2, 2019 at 8:51 $("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; </script>

    in html

    <a href="#top">go top</a>
    

    With window.scrollTo(0, 0); is very fast
    so i tried the Mark Ursino example, but in Chrome nothing happens
    and i found this

    $('.showPeriodMsgPopup').click(function(){
        //window.scrollTo(0, 0);
        $('html').animate({scrollTop:0}, 'slow');//IE, FF
        $('body').animate({scrollTop:0}, 'slow');//chrome, don't know if Safari works
        $('.popupPeriod').fadeIn(1000, function(){
            setTimeout(function(){$('.popupPeriod').fadeOut(2000);}, 3000);
    

    tested all 3 browsers and it works
    i'm using blueprint css
    this is when a client clicks "Book now" button and doesn't have the rental period selected, slowly moves to the top where the calendars are and opens a dialog div pointing to the 2 fields, after 3sec it fades

    Thanks for pointing out you need to target both html and body. I was only doing it for html and wondering why it didn't work in Chrome. – Jared Mar 10, 2011 at 20:42

    Another solution is JavaScript window.scrollTo method :

     window.scrollTo(x-value, y-value);
    

    Parameters :

  • x-value is the pixel along the horizontal axis.
  • y-value is the pixel along the vertical axis.
  • that is a legitimate way to use stackoverflow - it's more practical to have it in one place. Joel Spolsky used re-use of existing answers as an example of how stackoverflow is supposed to work at one point. If you are interested I can try and find the blog post – Edgar H Jan 25, 2018 at 13:25

    A lot of users recommend selecting both the html and body tags for cross-browser compatibility, like so:

    $('html, body').animate({ scrollTop: 0 }, callback);
    

    This can trip you up though if you're counting on your callback running only once. It will in fact run twice because you've selected two elements.

    If that is a problem for you, you can do something like this:

    function scrollToTop(callback) {
        if ($('html').scrollTop()) {
            $('html').animate({ scrollTop: 0 }, callback);
            return;
        $('body').animate({ scrollTop: 0 }, callback);
    

    The reason this works is in Chrome $('html').scrollTop() returns 0, but not in other browsers such as Firefox.

    If you don't want to wait for the animation to complete in the case that the scrollbar is already at the top, try this:

    function scrollToTop(callback) {
        if ($('html').scrollTop()) {
            $('html').animate({ scrollTop: 0 }, callback);
            return;
        if ($('body').scrollTop()) {
            $('body').animate({ scrollTop: 0 }, callback);
            return;
        callback();
    let topBtn = document.querySelector(".top-btn");
    // On Click, Scroll to the page's top, replace 'smooth' with 'auto' if you don't want smooth scrolling
    topBtn.onclick = () => window.scrollTo({ top: 0, behavior: "smooth" });
    // On scroll, Show/Hide the btn with animation
    window.onscroll = () => window.scrollY > 500 ? topBtn.style.opacity = 1 : topBtn.style.opacity = 0
    body {
      background-color: #111;
      height: 5000px;
    .top-btn {
      all: unset; 
      position: fixed;
      right: 20px;
      bottom: 20px;
      cursor: pointer;
      transform:scale(1.8);
      opacity: 0;
      transition: .3s;
    
    <button class="top-btn">🔝</button>
    $(".scrolltop").click(function() {
      $("html, body").animate({ scrollTop: 0 }, "slow");
      return false;
    
    .section{
     height:400px;
    .section1{
      background-color: #333;
    .section2{
      background-color: red;
    .section3{
      background-color: yellow;
    .section4{
      background-color: green;
    .scrolltop{
      position:fixed;
      right:10px;
      bottom:10px;
      color:#fff;
    <title>Scroll top demo</title>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    </head>
    <div class="content-wrapper">
    <div class="section section1"></div>
    <div class="section section2"></div>
    <div class="section section3"></div>
    <div class="section section4"></div>
    <a class="scrolltop">Scroll top</a>
    </body>
    </html>
    While this code may answer the question, providing information on how and why it solves the problem improves its long-term value – L_J Jul 14, 2018 at 7:53 In web page any user will click on scroll top button then then page will scroll top top with animation. – arvinda kumar Jul 21, 2018 at 5:57 What he is stating is true, and I believe it's a great answer as that version of jQuery already comes with support for scrolling .. if you open the JS file you will find the explanation there.. just need to target the class // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { – Jean G.T Aug 5, 2021 at 7:53 Note that when you don't use Firefox this won't work. You get an error when only giving one argument (Error: Not enough arguments [nsIDOMWindow.scrollTo]). – Husky Nov 14, 2012 at 13:57

    I write an animated solution on Codepen

    Also, you can try another solution with CSS scroll-behavior: smooth property.

    html {
        scroll-behavior: smooth;
    @media (prefers-reduced-motion: reduce) {
        html {
            scroll-behavior: auto;
    

    Why don't you use JQuery inbuilt function scrollTop :

    $('html, body').scrollTop(0);//For scrolling to top
    $("body").scrollTop($("body")[0].scrollHeight);//For scrolling to bottom
    

    Short and simple!

    Unfortunately, it's not the best solution since you are changing location physically in that case instead of scrolling the page. That might cause issues if location is important (in case of using Angular routing or so) – Yaroslav Rogoza Dec 17, 2015 at 15:50 @YaroslavRogoza is correct. While it may work in simple cases, I would not recommend this solution. Location is becoming increasingly important and single-page apps extensively use the hash to handle navigation. You would immediately introduce a side-effect bug when either adding hash based navigation after this or this to hash based navigation. – Andrew Grothe May 9, 2016 at 23:23

    Motivation

    This simple solution works natively and implements a smooth scroll to any position.

    It avoids using anchor links (those with #) that, in my opinion, are useful if you want to link to a section, but are not so comfortable in some situations, specially when pointing to top which could lead to two different URLs pointing to the same location (http://www.example.org and http://www.example.org/#).

    Solution

    Put an id to the tag you want to scroll to, for example your first section, which answers this question, but the id could be placed everywhere in the page.

    <section id="top"> <!-- your content --> </section> <div id="another"><!-- more content --></div>

    Then as a button you can use a link, just edit the onclick attribute with a code like this.

    <a onclick="document.getElementById('top').scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })">Click me</a>
    

    Where the argument of document.getElementById is the id of the tag you want to scroll to after click.

    @HugoStivenLagunaRueda you welcome, I found it on MDN, so thanks to Mozilla. It is awesome how many things are already there, supported natively. I love vanilla JS. – Gianluca Casati May 21, 2018 at 14:03

    If you don't want smooth scrolling, you can cheat and stop the smooth scrolling animation pretty much as soon as you start it... like so:

       $(document).ready(function() {
          $("a[href='#top']").click(function() {
              $("html, body").animate({ scrollTop: 0 }, "1");              
              $('html, body').stop(true, true);
              //Anything else you want to do in the same action goes here
              return false;                              
    

    I've no idea whether it's recommended/allowed, but it works :)

    When would you use this? I'm not sure, but perhaps when you want to use one click to animate one thing with Jquery, but do another without animation? ie open a slide-in admin login panel at the top of the page, and instantly jump to the top to see it.