Skip to content

Instantly share code, notes, and snippets.

@ahaywood
Last active November 7, 2018 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahaywood/d628596f4a5e7487c26b83096fd0530f to your computer and use it in GitHub Desktop.
Save ahaywood/d628596f4a5e7487c26b83096fd0530f to your computer and use it in GitHub Desktop.
JS: Scroll to Top

Requirements

Make sure you're including jQuery within the project.

Quick Use

The link that you want the user to click, trigger the scroll, needs to have a class of js-scroll-to-top:

<a href="#" class="js-scroll-to-top">Back to Top</a>

At the top of your page, right after the body tag, include an empty div with an ID of top:

<div id="#top"></div>
var lastScrollTop = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
// downscroll code
$(".js-back-to-the-top").addClass("scroll-down");
} else if (st < 25) {
// upscroll code
$(".js-back-to-the-top").removeClass("scroll-down");
}
lastScrollTop = st;
});
$('.js-scroll-to-top').click(function(e){
e.preventDefault(); // prevent the default browser action
var goto = $('#top'); // grab the #top element
var contentPosTop = $(goto).position().top - 50; // determine the position from the top of the page
// Animate to that position
$('html, body').stop().animate({
scrollTop: contentPosTop
}, 1500);
});
.back-to-the-top {
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.back-to-the-top.scroll-down {
opacity: 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment