Creating a smooth scroll “Back to Top” button using jQuery

Creating a smooth scroll “Back to Top” button using jQuery

Back to Top Demo Screenshot

Using jQuery and just a few lines of code, you can create simple and user-friendly “Back to Top” buttons which display when the user starts to scroll down a web page; and when clicked, smoothly scrolls the user automatically back to the top.

The two jQuery methods we’ll be using is the scroll() event to detect when a user is scrolling in the web page; and the animate() method to perform the animation when the user clicks the “Back to Top” button.

If you are not designing your “Back to Top” button yourself, there are free resources you can try such as IconMonstr and IconFinder to find one.

For the button itself, you may wish to position it absolutely in a specific area of your page. Here is example CSS code to accomplish this:

#quickjump {
display: none;
position: absolute;
top: 33%;
right: 3%;
width: 32px;
height: 32px;
cursor: pointer;
background: url(‘up-arrow.png’) no-repeat;
}

As you can see, this element will be hidden by default through CSS, because if we were to hide this with JavaScript, the element may be visible for a split second as the DOM is loading, and would remain visible if a user has JavaScript disabled, of course.

On to the jQuery code, and this is just as easy:

$(window).scroll(function() {
if($(window).scrollTop() > 250) { // in pixels
$(‘#quickjump’).fadeIn(800); // 800 milliseconds for the fade in effect
}
else {
$(‘#quickjump’).fadeOut(‘fast’); // 200 milliseconds for the fade out effect
}
});

This code is to either display or hide the button depending on how far the user has scrolled down. If the user scrolls back up the page and is less than 250 pixels from the top, the button will fade out.

$(‘#quickjump’).click(function() {
$(‘body,html’).animate({scrollTop: 0});
});

And that’s all there is to it. It’s that simple. Make sure all your jQuery code is contained within the $(document).ready() method to make sure it is only executed once the DOM has fully loaded:

$(document).ready(function() {
// your code here
});

Ben Stones

Sharing

Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.