Scroll to the top of the page using JavaScript?
Asked Answered
K

50

2030

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.

Krawczyk answered 17/7, 2009 at 17:59 Comment(3)
2019, to avoid “This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning” use my script https://mcmap.net/q/45753/-what-is-the-alternative-to-quot-scroll-linked-positioning-effect-quot-to-prevent-performance-issuesAbide
SO should delete jQuery answers.Brunswick
Try this css html,body{ scroll-behavior: smooth} and some script for scroll top window.scrollTo(0,0)Kiushu
P
2674

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.
Pitchy answered 17/7, 2009 at 18:42 Comment(10)
That was my point, if you don't need to animate smooth scrolling then you don't need to use jQuery.Pitchy
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 :(Khalif
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: #4147612Selenodont
Working for me in Firefox 40 and Chrome 44 (to address Mikhail's comment)Irritated
and what if I want to scroll to the bottom of the page ?Vicinage
Scroll to the bottom of the page window.scrollTo(0, document.body.scrollHeight);Linehan
Even if you need to animate. scrollTo now takes an options as param: scrollTo({left: 0, top: 0, behavior: 'smooth'}) see MDNPotbelly
I tried window.scrollTo(0, 0) and I get "undefined"Karyotype
could you please help on related question please? #58653546Configurationism
you have just to add this CSS to get a smooth scroll :) html { scroll-behavior: smooth; }Musclebound
H
1470

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.

Hadrian answered 17/7, 2009 at 19:43 Comment(9)
+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.Obovate
scrollTop is not function, it is a property of the window elementTrici
This does not work correctly when using animate's complete callback, as it will run it twice.Dexterous
$("html, body").animate({ scrollTop: 0 }, "slow"); is workingErb
Do you know why it's necessary to add html & body in the selector?Violone
@user751564: It's not necessary, check https://mcmap.net/q/45756/-is-it-possible-to-animate-scrolltop-with-jquery.Allaround
So you've added html to the selector because, although by default it's in body, it may be moved outside, to the html?Violone
"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.Gynandry
@jalchr Actually, window.pageYOffset would be the property of the window e̶l̶e̶m̶e̶n̶t̶ object.Acedia
V
410

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

Villanovan answered 23/10, 2018 at 11:59 Comment(5)
You may still need to polyfill support for the ScrollOptions (for certain browsers): github.com/iamdustan/smoothscrollQuantic
I like this solution a lot.Latinalatinate
Can someone test this on Safari or Internet Explorer and see if it's working fine? ThanksSiddon
@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).Villanovan
This is the best answer. We can use document.body.scrollHeight for the top value if one wants to scroll to the bottom.Cassareep
C
214

Try this to scroll on top

<script>
 $(document).ready(function(){
    $(window).scrollTop(0);
});
</script>
Calla answered 21/5, 2012 at 7:45 Comment(1)
this is the same: if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; }Confirm
J
118

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>
Justice answered 17/7, 2009 at 18:51 Comment(5)
+1 This is good if you need to navigate to specific element rather just to the top.Anticyclone
Use '<a href="#">Top</a>' to jump to the top of the page.From
This seems to be the best way to go when dealing with SPAsXylia
Nice! Is there a way to make it smooth scroll ?Electron
This is not going to work if you call another button by using getElementById in the middle of a page.Kerrison
W
76

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);
Westley answered 23/4, 2012 at 9:53 Comment(0)
F
59

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));
    }
})();
Fetor answered 29/5, 2015 at 10:49 Comment(0)
V
46
<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' });
Via answered 24/7, 2014 at 6:52 Comment(4)
Are you sure duration as string in animate function works?Ridgley
You can't use a string for the duration in the animate function, instead you should use: $('html, body').animate({scrollTop:(scroll_pos)}, 2000);Dockery
What is the point of wrapping 0 in parenthesis? ((0)) will simply evaluate to 0.Saimon
Yes @Jack, you can.Via
M
38

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

Myrick answered 2/10, 2014 at 10:0 Comment(3)
The question explicitly asks for a jQuery solution though. so not strangeKhalif
Best solution for me. No plugins, no bulky jquery library just straightforward javascript. KudosIntercurrent
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.Veronaveronese
D
36

Scroll to top of page with animation:

window.scrollTo({ top: 0, behavior: 'smooth' });
Dry answered 25/4, 2022 at 7:33 Comment(0)
L
33
<script>

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

in html

<a href="#top">go top</a>
Lilas answered 14/2, 2014 at 16:44 Comment(0)
S
30

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

Snook answered 1/9, 2010 at 13:1 Comment(4)
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.Theiss
The body animation does work in Safari, so I'm updating your answer accordingly.Bailar
"Tested all 3 browsers"? Midori, LuaKit and Konqueror, right? :pTabling
Why not just do $('html', 'body').animate({scrollTop:0}) instead of adding two lines?Defalcate
D
30

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.
Dichromaticism answered 11/9, 2017 at 10:37 Comment(3)
copycat... see users answers... This is just a compilation of the top 2 answers....Venomous
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 postLaith
should mention your 1st solution requires jQuery.Crafton
B
26

Smooth scrolling & animation with vanilla Javascript, without jQuery

// Get the element
let topBtn = document.querySelector(".top-btn");

// On Click, Scroll to the page's top, replace 'smooth' with 'instant' 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 = () => topBtn.style.opacity = window.scrollY > 500 ? 1 : 0;
body {
  background-color: #111;
  height: 5000px;
  font-size:5rem;
  color: white;
}

.top-btn {
  all: unset;
  font-size:1.5rem; 
  position: fixed;
  right: 20px;
  bottom: 20px;
  cursor: pointer;
  transform:scale(1.8);
  opacity: 0;
  transition: .3s;
}
<button class="top-btn">🔝</button>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi." "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla facilisi. Quisque vel sem vel dui sodales cursus. Vivamus nec erat eu nisl facilisis laoreet vel a dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nunc vel elit eget mauris gravida dictum non at eros. Sed nec massa eu justo interdum fringilla. Fusce nec dolor auctor, tincidunt purus id, feugiat justo. Pellentesque tincidunt, mauris a dapibus eleifend, libero lorem congue elit, eget iaculis odio metus non mi."</p>

With React.js

import { useEffect, useState } from 'react';

export default function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  const handleScroll = () => setIsVisible(window.scrollY > 500);
  const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' });


  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <button
      style={{
        all: 'unset',
        fontSize: '1.5rem',
        position: 'fixed',
        right: '20px',
        bottom: '20px',
        cursor: 'pointer',
        transform: 'scale(1.8)',
        opacity: isVisible ? 1 : 0,
        transition: '0.3s',
      }}
      onClick={scrollToTop}
    >
      🔝
    </button>
  );
}
Brunswick answered 22/5, 2020 at 23:59 Comment(0)
L
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();
}
Lu answered 31/10, 2014 at 18:56 Comment(0)
G
23

The old #top can do the trick

document.location.href = "#top";

Works fine in FF, IE and Chrome

Goodrich answered 1/12, 2014 at 2:29 Comment(2)
Nice! Is there a way to make it smooth scroll ?Electron
you should avoid navigation based solutions, see comments on Sriramajeyam's answer.Ethelinda
P
22

This will work:

window.scrollTo(0, 0);

Proposition answered 19/4, 2018 at 5:13 Comment(1)
This was the best answerPreterition
M
20

$(".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;
}
<html>
<head>
<title>Scroll top demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<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>
</div>

</body>
</html>
Molybdate answered 14/7, 2018 at 7:45 Comment(5)
While this code may answer the question, providing information on how and why it solves the problem improves its long-term valueGauhati
Explain your answer!Readymix
In web page any user will click on scroll top button then then page will scroll top top with animation.Molybdate
Why animate() instead of jquery scroll()?Fugato
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 ) {Suchlike
S
19

Non-jQuery solution / pure JavaScript:

document.body.scrollTop = document.documentElement.scrollTop = 0;
Schneider answered 30/1, 2014 at 16:25 Comment(0)
M
17

The equivalent solution in TypeScript may be as the following

   window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
Maniacal answered 20/7, 2020 at 7:54 Comment(2)
Your snippet has nothing to do with TypeScript and work perfectly fine in Javascript.Mottled
Your code Works perfectSenarmontite
P
16

Try this

<script>
    $(window).scrollTop(100);
</script>
Perrotta answered 1/12, 2011 at 6:51 Comment(0)
C
16

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

Cheng answered 31/7, 2012 at 20:53 Comment(1)
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]).Debit
F
14

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;
    }
}
Farhi answered 5/11, 2019 at 15:28 Comment(0)
C
11

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.

Couchant answered 8/8, 2017 at 7:42 Comment(0)
G
8

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.

Granitite answered 25/6, 2015 at 11:22 Comment(2)
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)Hyperborean
@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.Ethelinda
I
8

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!

Instantly answered 20/3, 2016 at 9:42 Comment(1)
You're just missing the link to the docSalicaceous
N
8

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.

Navel answered 9/5, 2018 at 8:46 Comment(2)
Thanks you! is great solutionPompom
@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.Navel
F
8

document.getElementById("elem").scrollIntoView();

Fulfillment answered 9/1, 2019 at 17:18 Comment(1)
Thanks a lot. The only one that worked for me, strange though. Many thanks.Unesco
R
7

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.

Renascent answered 13/5, 2014 at 16:53 Comment(0)
P
7

Simply use this script for scroll to top direct.

<script>
$(document).ready(function(){
    $("button").click(function(){
        ($('body').scrollTop(0));
    });
});
</script>
Pyriphlegethon answered 27/9, 2017 at 11:31 Comment(0)
G
7

You can use javascript's built in function scrollTo:

function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}
<button onclick="scroll">Scroll</button>
Geithner answered 28/5, 2020 at 19:58 Comment(0)
S
5

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.

Saturnian answered 17/7, 2009 at 18:9 Comment(0)
G
5

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;
Gramicidin answered 14/2, 2018 at 12:21 Comment(0)
T
4

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>
Trisa answered 1/2, 2014 at 19:35 Comment(0)
U
4
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;
    });
}
Uniform answered 21/11, 2014 at 21:11 Comment(0)
R
4
document.getElementsByTagName('html')[0].scrollIntoView({ behavior: "smooth" });
Radiobiology answered 7/3, 2022 at 22:10 Comment(0)
K
3

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);
        }
Kirt answered 19/10, 2015 at 3:22 Comment(0)
V
3

Try this

<script>
  $(function(){
   $('a').click(function(){
    var href =$(this).attr("href");
   $('body, html').animate({
     scrollTop: $(href).offset().top
     }, 1000)
  });
 });
 </script>
Vacation answered 27/12, 2015 at 22:18 Comment(0)
K
3

Try this solution using simple css just put css scroll-behavior:smooth on html and body as i have applied in css. that's it

document.querySelector('a').onclick = function() {
  window.scrollTo(0,0)
}
html,body{
  scroll-behavior: smooth;
}
a{
  background-color: red;
  color:#fff;
  border-radius: 10px;
  margin:10px 0;
  display: inline-block;
  padding:10px 20px;
}
<p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p><p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<a>Scroll to Top</a>

I Hope this will help you a lot. Please do let me know your thoughts

Kiushu answered 25/12, 2022 at 7:59 Comment(0)
A
2

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;
    });
});``
Adduce answered 19/9, 2013 at 15:1 Comment(0)
F
2

Just Try, no need other plugin / frameworks

document.getElementById("jarscroolbtn").addEventListener("click", jarscrollfunction);

function jarscrollfunction() {
  var body = document.body; // For Safari
  var html = document.documentElement; // Chrome, Firefox, IE and Opera 
  body.scrollTop = 0; 
  html.scrollTop = 0;
}
<button id="jarscroolbtn">Scroll contents</button> 
html, body {
  scroll-behavior: smooth;
}
File answered 26/3, 2019 at 13:1 Comment(0)
N
2

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>
Nomadize answered 13/12, 2020 at 9:26 Comment(2)
The OP asked for javascript and did not state the causing event is a clck on an anchor.Checky
Edit your answer to specifically start with "If the scrolling is always triggered by a click on an anchor, then..."Gramicidin
A
2

Back to Top with AplineJS and TailwindCSS:

<button
    x-cloak
    x-data="{scroll : false}"
    @scroll.window="document.documentElement.scrollTop > 20 ? scroll = true : scroll = false"
    x-show="scroll" @click="window.scrollTo({top: 0, behavior: 'smooth'})"
    type="button"
    data-mdb-ripple="true"
    data-mdb-ripple-color="light"
    class="fixed inline-block p-3 text-xs font-medium leading-tight text-white uppercase transition duration-150 ease-in-out bg-blue-600 rounded-full shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg bottom-5 right-5"
    id="btn-back-to-top"
    x-transition.opacity
>
    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M3.293 9.707a1 1 0 010-1.414l6-6a1 1 0 011.414 0l6 6a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L4.707 9.707a1 1 0 01-1.414 0z" clip-rule="evenodd" />
    </svg>
</button>
Alexei answered 8/5, 2022 at 12:53 Comment(0)
H
1

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/

Hohenstaufen answered 26/8, 2017 at 10:39 Comment(0)
B
1

Shortest

location='#'

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

Blackcap answered 13/5, 2020 at 13:4 Comment(0)
P
0

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);
Parenthesize answered 25/6, 2017 at 11:2 Comment(0)
M
0

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

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');
    }
});
.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;

}
    <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>
Manatee answered 24/2, 2021 at 15:30 Comment(0)
R
0

Please check the below code, surely it will be helpful. :)

document.querySelector('.sample-modal .popup-cta').scrollIntoView(true);
document.querySelector('.sample-modal').style.scrollPadding = '50px'; //to move to the top when scrolled up.
Retrieval answered 14/4, 2022 at 5:25 Comment(0)
P
0

This works for me:

document.documentElement.scrollIntoView({ behavior: "smooth" })
Pickwickian answered 13/3, 2023 at 18:1 Comment(1)
I achieved using React useRef, theRef.current.props.node.ownerDocument.documentElement and so on...Goosy
C
-1

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.

Carricarriage answered 26/12, 2015 at 0:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.