[javascript] smooth scroll to top

I've bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors in the page with a .js file attatched to my site but I cannot use an anchor for the top, because I'm using a template from a free hosting site with built in page building tools that do not allow me to edit above the body area.

Here's where I got the smooth scrolling. I've been trying to set up "smoothly-scroll-to-an-element-without-a-jquery-plugin" but I have no idea how to arrange it obviously after countless attempts. I've also used window.scrollTo(0, 0); but it scrolls instantly. Thanks!

In addition: http://jsfiddle.net/WFd3V/ - the code would probably be the tag class="smoothScroll" since my other element uses that, but I don't know how to mix it with the href="javascript:window.scrollTo(0,0);" , or anything else that would bring the page to the top without an anchor.

This question is related to javascript

The answer is


Came up with this solution:

function scrollToTop() {
let currentOffset = window.pageYOffset;
const arr = [];

for (let i = 100; i >= 0; i--) {
    arr.push(new Promise(res => {
            setTimeout(() => {
                    res(currentOffset * (i / 100));
                },
                2 * (100 - i))
        })
    );
}

arr.reduce((acc, curr, index, arr) => {
    return acc.then((res) => {
        if (typeof res === 'number')
            window.scrollTo(0, res)
        return curr
    })
}, Promise.resolve(currentOffset)).then(() => {
    window.scrollTo(0, 0)
})}

I just customized BootPc Deutschland's answer

You can simply use

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('body,html').animate({
            scrollTop: 0
        }, 800);
    $('#btn-go-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 800);
        return false;
    });
}); 
</script>

this will help you to smoothly scroll to the top of the page.

and for styling

#btn-go-to-top {
opacity: .5;
width:4%;
height:8%;
display: none;
position: fixed;
bottom: 5%;
right: 3%;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 10px;
 border-radius: 50%;
}

#btn-go-to-top:hover {
opacity: 1;
}
.top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
}

this styling makes the button arrive at the bottom-right of the page.

and in your page you can add the button to go to top like this

<div id="btn-go-to-top" class="text-center top">
<img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
</div>

hope this help you.if you have any doubts you are always free to ask me


I think the simplest solution is:

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

If you wanted instant scrolling then just use:

window.scrollTo({top: 0});

Can be used as a function:

// Scroll To Top

function scrollToTop() {

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

}

Or as an onclick handler:

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

Here is my proposal implemented with ES6

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();

Tip: for slower motion of the scrolling, increase the hardcoded number 8. The bigger the number - the smoother/slower the scrolling.


You can simply use

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("gotoTop").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("gotoTop").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#gotoTop {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#gotoTop:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_


You should start using jQuery or some other js lib. It's way easier than js, and you can use it as a shorthand for most js instead of actually long, drawn out js.

Simply put <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> (or whatever the latest google cdn is https://developers.google.com/speed/libraries/devguide#jquery) in your <head>.

Then, inside your event code (much easier if you use jQuery: $.click() for buttons, $.change() for checkboxes, selects, radios...), put the code from your second link looking more like

$('#theIDofTheButtonThatTriggersThisAnimation').click(function(){
    $('#theIDofTheElementYouWantToSmoothlyScroll').animate({
        scrollTop: 0
    }, 2000);
});

However, if you're trying to do animations, I recommend you look into some basic css properties like position:absolute and position:relative to keep from going crazy.


I'm still not quite sure what's going on in your code because it's very non-standard relative to how things are done now with css & jQuery. I'd break it down into something simple to learn the general concept.

For your example, you should build off of my animation example, how I learned: https://stackoverflow.com/a/12906254/1382306

I think you're trying to move your text up and down based upon a $.click(). In the fiddle in my answer, it slides left and right. You can easily reformat up and down by using the css top property instead of left.

Once you figure out how to move the entire div up and down, you can make a relative container to hold all of the content absolute divs and manipulate all content divs with a loop by setting their tops. Here's a quick primer on absolute in relative: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

All of my animations have relative containers and absolute content. It's how I made a custom gridview plugin that can instantly zip through an entire database.

Also, there really is no overuse of divs when it comes to animating. Trying to make 1 div do everything is a nightmare.

Try to see if you can reformat my fiddle into a vertical slide out. Once you've done that, research absolute in relative a little. If you have any more problems, just ask another question.

Change your thinking to these philosophies, and you'll start flying through this type of coding.


also used below:

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

Some time has passed since this was asked.

Now it is possible to not only specify number to window.scroll function, but also pass an object with three properties: top, left and behavior. So if we would like to have a smooth scroll up with native JavaScript, we can now do something like this:

let button = document.querySelector('button-id');
let options = {top: 0, left: 0, behavior: 'smooth'}; // left and top are coordinates
button.addEventListener('click', () => { window.scroll(options) });

https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll


theMaxx answer works in nuxt/vue, smooth scrolling is default behavior

<button @click=scrollToTop()>Jump to top of page

  methods: {
    scrollToTop() {
      window.scrollTo({ top: 0 });
    }
  }

Hmm comment function off for me,

try this

_x000D_
_x000D_
$(document).ready(function(){
    $("#top").hide();
    $(function toTop() {
        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('#top').fadeIn();
            } else {
                $('#top').fadeOut();
            }
        });

        $('#top').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    });         
            
            
    
    });
_x000D_
#top {
  float:right;
  width:39px;
  margin-top:-35px; 
}
#top {
    transition: all 0.5s ease 0s;
    -moz-transition: all 0.5s ease 0s;
    -webkit-transition: all 0.5s ease 0s;
    -o-transition: all 0.5s ease 0s;
    opacity: 0.5;
    display:none;
    cursor: pointer;
}
#top:hover {
    opacity: 1;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="top" onclick="toTop()"><img src="to_top.png" alt="no pic "/> klick to top</div>
_x000D_
_x000D_
_x000D_


window.scroll({top: 0, behavior: "smooth"})

Just use this piece of code and it will work perfectly, You can wrap it into a method or event.


Pure Javascript only

_x000D_
_x000D_
var t1 = 0;_x000D_
window.onscroll = scroll1;_x000D_
_x000D_
function scroll1() {_x000D_
  var toTop = document.getElementById('toTop');_x000D_
  window.scrollY > 0 ? toTop.style.display = 'Block' : toTop.style.display = 'none';_x000D_
}_x000D_
_x000D_
function abcd() {_x000D_
  var y1 = window.scrollY;_x000D_
  y1 = y1 - 1000;_x000D_
  window.scrollTo(0, y1);_x000D_
  if (y1 > 0) {_x000D_
    t1 = setTimeout("abcd()", 100);_x000D_
  } else {_x000D_
    clearTimeout(t1);_x000D_
  }_x000D_
}
_x000D_
#toTop {_x000D_
  display: block;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 20px;_x000D_
  font-size: 48px;_x000D_
}_x000D_
_x000D_
#toTop {_x000D_
  transition: all 0.5s ease 0s;_x000D_
  -moz-transition: all 0.5s ease 0s;_x000D_
  -webkit-transition: all 0.5s ease 0s;_x000D_
  -o-transition: all 0.5s ease 0s;_x000D_
  opacity: 0.5;_x000D_
  display: none;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
#toTop:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<p>your text here</p>_x000D_
<img id="toTop" src="http://via.placeholder.com/50x50" onclick="abcd()" title="Go To Top">
_x000D_
_x000D_
_x000D_


Elegant easy solution using jQuery.

<script>
    function call() {
        var body = $("html, body");
        body.stop().animate({scrollTop:0}, 500, 'swing', function() {
        });
    }
</script>

and in your html : <div onclick="call()"><img src="../img/[email protected]"></div>