[javascript] Scroll to the top of the page using JavaScript?

How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.

This question is related to javascript scroll

The answer is


There is no need to javascript, event if you wanted to animate the scroll action!

CSS:

html {
    scroll-behavior: smooth;
}

HTML:

<html>
  <body>
     <a id="top"></a>
     <!-- your document -->
     <a href="#top">Jump to top of page</a>
  </body>
</html>

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!


You can try using JS as in this Fiddle http://jsfiddle.net/5bNmH/1/

Add the "Go to top" button in your page footer:

<footer>
    <hr />
    <p>Just some basic footer text.</p>
    <!-- Go to top Button -->
    <a href="#" class="go-top">Go Top</a>
</footer>

You could simply use a target from your link, such as #someid, where #someid is the div's id.

Or, you could use any number of scrolling plugins that make this more elegant.

http://plugins.jquery.com/project/ScrollTo is an example.


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.


The old #top can do the trick

document.location.href = "#top";

Works fine in FF, IE and Chrome


$(document).scrollTop(0); also works.


<script>
$(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' });

This will work:

window.scrollTo(0, 0);


When top scroll is top less than limit bottom and bottom to top scroll Header is Sticky. Below See Fiddle Example.

var lastScroll = 0;

$(document).ready(function($) {

$(window).scroll(function(){

 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {

        $("header").removeClass("menu-sticky");

    } 
    if (scroll == 0) {
    $("header").removeClass("menu-sticky");

    }
    else if (scroll < lastScroll - 5) {


        $("header").addClass("menu-sticky");

    }
    lastScroll = scroll;
    },0);
    });
   });

https://jsfiddle.net/memdumusaib/d52xcLm3/


Shortest

location='#'

This solution is improvement of pollirrata answer and have some drawback: no smooth scroll and change page location, but is shortest


Pure JavaScript solution:

function scrollToTop() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
});

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;
    }
}

None of the answers above will work in SharePoint 2016.

It has to be done like this : https://sharepoint.stackexchange.com/questions/195870/

var w = document.getElementById("s4-workspace");
w.scrollTop = 0;

Smooth scrolling With Pure Javascript, Without jQuery

_x000D_
_x000D_
// Get The Id
var topPage = document.getElementById(`top-page`)

// On Click, Scroll to the Top of Page
topPage.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' })

// On scroll, Show/Hide the button
window.onscroll = () => {
  window.scrollY > 500
    ? (topPage.style.display = `block`)
    : (topPage.style.display = `none`)
}
_x000D_
body {
    background-color: #111;
    height:5000px;
}


#top-page {
    all:unset;
    position: fixed;
    right: 20px;
    bottom: 20px;
    cursor: pointer;
    font-size: 2rem;
    outline: none;
    display: none;
}
_x000D_
<button id="top-page"></button>
_x000D_
_x000D_
_x000D_


Active all Browser. Good luck

var process;
        var delay = 50; //milisecond scroll top
        var scrollPixel = 20; //pixel U want to change after milisecond
        //Fix Undefine pageofset when using IE 8 below;
        function getPapeYOfSet() {
            var yOfSet = (typeof (window.pageYOffset) === "number") ? window.pageYOffset : document.documentElement.scrollTop;
            return yOfSet;
        }



        function backToTop() {
            process = setInterval(function () {
                var yOfSet = getPapeYOfSet();
                if (yOfSet === 0) {
                    clearInterval(process);
                } else {
                    window.scrollBy(0, -scrollPixel);
                }
            }, delay);
        }

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


You can use javascript's built in function scrollTo:

_x000D_
_x000D_
function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}
_x000D_
<button onclick="scroll">Scroll</button>
_x000D_
_x000D_
_x000D_


Non-jQuery solution / pure JavaScript:

document.body.scrollTop = document.documentElement.scrollTop = 0;

Simply use this script for scroll to top direct.

<script>
$(document).ready(function(){
    $("button").click(function(){
        ($('body').scrollTop(0));
    });
});
</script>

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.

<body>
  <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.


Try this

<script>
  $(function(){
   $('a').click(function(){
    var href =$(this).attr("href");
   $('body, html').animate({
     scrollTop: $(href).offset().top
     }, 1000)
  });
 });
 </script>?

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);

The equivalent solution in TypeScript may be as the following

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

Try this

<script>
    $(window).scrollTop(100);
</script>

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.


A simple example of scroll to (using html is much more efficient but here is how to do it with JavaScript):

_x000D_
_x000D_
const btn = document.querySelector('.btn');
btn.addEventListener('click',()=>{
      window.scrollTo({
       left: 0,
       top: 0,
})})
window.addEventListener('scroll', function() {
    const scrollHeight = window.pageYOffset;
    if (scrollHeight > 500) {
        btn.classList.add('show-link');
    } else {
        btn.classList.remove('show-link');
    }
});
_x000D_
.section {
    padding-bottom: 5rem;
    height: 90vh;
}
.btn {
    position: fixed;
    bottom: 3rem;
    right: 3rem;
    background: blue;
    width: 2rem;
    height: 2rem;
    color: #fff;
    visibility: hidden;
    z-index: -100;
}
.show-link {
    visibility: visible;
    z-index: 100;
}

.title h2 {
    text-align: center;

}
_x000D_
    <section class="section">
      <div class="title">
        <h2>Section One</h2>
      </div>
    </section>
    <section class="section">
      <div class="title">
        <h2>Section Two</h2>
      </div>
    </section>
    <section  class="section">
      <div class="title">
        <h2>Section Three</h2>
      </div>
    </section>
    <a class="btn">
    </a>
_x000D_
_x000D_
_x000D_


You dont need JQuery. Simply you can call the script

window.location = '#'

on click of the "Go to top" button

Sample demo:

output.jsbin.com/fakumo#

PS: Don't use this approach, when you are using modern libraries like angularjs. That might broke the URL hashbang.


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();
}

Funnily enough, most of these did not work for me AT ALL, so I used jQuery-ScrollTo.js with this:

wrapper.find(".jumpToTop").click(function() {
    $('#wrapper').ScrollTo({
        duration: 0,
        offsetTop: -1*$('#container').offset().top
    });
});

And it worked. $(document).scrollTop() was returning 0, and this one actually worked instead.


_x000D_
_x000D_
$(".scrolltop").click(function() {_x000D_
  $("html, body").animate({ scrollTop: 0 }, "slow");_x000D_
  return false;_x000D_
});
_x000D_
.section{_x000D_
 height:400px;_x000D_
}_x000D_
.section1{_x000D_
  background-color: #333;_x000D_
}_x000D_
.section2{_x000D_
  background-color: red;_x000D_
}_x000D_
.section3{_x000D_
  background-color: yellow;_x000D_
}_x000D_
.section4{_x000D_
  background-color: green;_x000D_
}_x000D_
.scrolltop{_x000D_
  position:fixed;_x000D_
  right:10px;_x000D_
  bottom:10px;_x000D_
  color:#fff;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Scroll top demo</title>_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div class="content-wrapper">_x000D_
<div class="section section1"></div>_x000D_
<div class="section section2"></div>_x000D_
<div class="section section3"></div>_x000D_
<div class="section section4"></div>_x000D_
<a class="scrolltop">Scroll top</a>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Try this to scroll on top

<script>
 $(document).ready(function(){
    $(window).scrollTop(0);
});
</script>

<script>

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

in html

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

document.getElementById("id of what you want to scroll to").scrollIntoView();

Edit: It's been a year and I'm still randomly getting reputation from this post lmao

Edit 2: Please stop editing the first edit out. At least ask me before editing my post.


Better solution with smooth animation:

// 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


If you want to do smooth scrolling, please try this:

$("a").click(function() {
     $("html, body").animate({ scrollTop: 0 }, "slow");
     return false;
});

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.

Just Try, no need other plugin / frameworks

_x000D_
_x000D_
document.getElementById("jarscroolbtn").addEventListener("click", jarscrollfunction);_x000D_
_x000D_
function jarscrollfunction() {_x000D_
  var body = document.body; // For Safari_x000D_
  var html = document.documentElement; // Chrome, Firefox, IE and Opera _x000D_
  body.scrollTop = 0; _x000D_
  html.scrollTop = 0;_x000D_
}
_x000D_
<button id="jarscroolbtn">Scroll contents</button> 
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
html, body {_x000D_
  scroll-behavior: smooth;_x000D_
}
_x000D_
_x000D_
_x000D_


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


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

<div id="jump_to_me">
    blah blah blah
</div>

<a target="#jump_to_me">Click Here To Destroy The World!</a>

Try this code:

$('html, body').animate({
    scrollTop: $("div").offset().top
}, time);

div => Dom Element where you want to move scroll.

time => milliseconds, define the speed of the scroll.


function scrolltop() {

    var offset = 220;
    var duration = 500;

    jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
            jQuery('#back-to-top').fadeIn(duration);
        } else {
            jQuery('#back-to-top').fadeOut(duration);
        }
    });

    jQuery('#back-to-top').click(function(event) {
        event.preventDefault();
        jQuery('html, body').animate({scrollTop: 0}, duration);
        return false;
    });
}

For scrolling to the element and element being at the top of the page

WebElement tempElement=driver.findElement(By.cssSelector("input[value='Excel']"));

            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", tempElement);

If you'd like to scroll to any element with an ID, try this:

$('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 700, 'swing', function () {
        window.location.hash = target;
    });
});``

smooth scroll, pure javascript:

(function smoothscroll(){
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
         window.requestAnimationFrame(smoothscroll);
         window.scrollTo (0,currentScroll - (currentScroll/5));
    }
})();