23
DecHello Guys, today I’m gonna teach you how to add a scroll to top button for your website using jQuery. But first of all, let’s figure out why we need this kind of a button for our website. Simply we need it for giving your website visitors a best user experience. When a page(s) of your website has more information, I meant if there is more content in your web page(s) and user scrolls down far away from the top, this button will be helpful to go to the top of the website at once without scrolling upwards.
If you are lazy to read this, download the demo I made directly. Let others understand the code with me then.
First, we will see the HTML code related to the button.
<a href="#" class="scrollToTop"></a>
So everyone knows that we add a link in HTML with <a> tag. Next, we need to style this using CSS.
.scrollToTop {
width:75px;
height:75px;
padding:10px;
text-decoration: none;
position:fixed;
bottom:50px;
right:15px;
display:none;
background: url('arrow_up.svg') no-repeat center center;
background-size: 50px 50px;
}
.scrollToTop:hover {
text-decoration:none;
}
As you can see, I have added styles to .scrollToTop class. I have fixed the position of this as it should always be displayed at the bottom right corner of our web page. It is placed at a 15px from the right and a 50px from the bottom of the browser window. The “display: none” is given because a user does not have to see this button before scrolling the page to some extent. I have used an SVG as the background image for this which shows us the up arrow. But you can use another image format if you want. Now let’s go to our jQuery part.
$(document).ready(function () {
//If user has scrolled more than 100px from the top, display the button
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function () {
$('html, body').animate({ scrollTop: 0 }, 800);
return false;
});
});
The ready event occurs when the DOM (document object model) has been loaded and the two functions inside .ready() method do their jobs when a user scrolls the page more than 100px and clicks the back to top button respectively. That’s all guys. Hope you enjoyed the tutorial. Thanks for reading…
Subscribe us and get latest news and updates to your inbox directly.