4

I want normal scroll to top for website.

The scroll to top link appears at the bottom of page(near footer) which only visible after 200px mouse scroll down and should be hidden when scroll back to top. WITHOUT JQUERY

Here is the demo

In this demo back to top is already at the bottom. Is there any way to show back to top link fixed as I mention above?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rushi Jagani
  • 160
  • 2
  • 12
  • I think this answer will help you: [link](http://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom) – tim.schurti Jan 10 '17 at 14:43

3 Answers3

4

if you want it as simple as possible, just use:

<a href="#" onClick="window.scrollTo(0,0)">

this will scroll you to the top of your site.

2

For this case, the MDN docs leave an awesome solution, we can now use the following example:

const el = document.getElementById('the-scroll-box');

el.scrollTo({
  top: 0,
  left: 0,
  behavior: 'smooth', // or can get `auto` variable
});

The behavior if have smooth value, the scrolling motion is smooth if have auto value the motion happen in one jump.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
1

Here is the answer

HTML

<a id="scroll_to_top_id"></a>

CSS

#scroll_to_top_id {
  display: none;
  position: fixed;
  right: 30px;
  bottom: 30px;
  background
}

PURE JAVASCRIPT(NO JQUERY)

/*
 *  Scroll To Top
 */

var your_header        = document.getElementById('header_id'),
    scroll_to_top   = document.getElementById('scroll_to_top_id');


window.onscroll = function(ev) {

    var  scrollTop = window.pageYOffset || document.body.scrollTop;
    if (scrollTop > your_header.offsetHeight + 100) {

        scroll_to_top.style.display = 'block';
    }
    else{
        scroll_to_top.style.display = 'none';   
    }
};

scroll_to_top.onclick = function () {
    scrollTo(document.body, 0, 100);
}

/*
 *  scroll to body top
 *  element, position and time duration
 */
function scrollTo(element, to, duration) {
        if (duration < 0) return;
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 2;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        scrollTo(element, to, duration - 2);
    }, 10);
}
Rushi Jagani
  • 160
  • 2
  • 12