This is a short tutorial on how to put a button on your web site that when clicked, will take the visitor to the top of the page in a smooth animation.
You can see how the button works by looking at the right side of my site. There should be a button there. If there isn’t a button there, scroll down a bit and it should appear. Try clicking on it π
I’ve also made a simple demo page. You can download the demo here.
Step 1
Let’s start by adding jQuery to a page. You do that by pasting this code into the head tag of your html document.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
This will tell the browser to load jQuery from Googles server when your page is loaded.
Step 2
Add this html code to the bottom of your html, just before the body tag closes.
<a id="toTop" href="#">Go to Top</a>
This is the button/link that will take the user to the top when clicked.
Step 3
Now we’ll add some CSS for the button. It should also go into your head tag. We want the button to be located to the right and positioned in the vertical center of the page.
<style type="text/css"> #toTop { display: block; position: fixed; top: 50%; right: 0; padding: 10px; border: 2px solid red; background: white; } </style>
By using position: fixed; When the user scrolls, the button will always appear at the same place on the page.
Step 4
Now we’ll add script tags and initate jQuery.
<script> $(document).ready(function(){ // Javascript code will go here. }); </script>
The second line “$(document).ready(function()” will tell the browser to run the code inside these brackets when the page loads.
I always test if jQuery is working by typing “alert(“jQuery is working!”);” inside the document.ready function. Like this:
$(document).ready(function(){ // Javascript code will go here. alert("jQuery is working!"); });
If it works, when your refresh your page you should get an alert “jQuery is working!”, if not, you should check if you loaded jQuery correctly.
Step 5
We can finally add the javascript that will make the page automatically scroll up when the button is clicked.
$(document).ready(function(){ // Hide the toTop button when the page loads. $("#toTop").css("display", "none"); // This function runs every time the user scrolls the page. $(window).scroll(function(){ // Check weather the user has scrolled down (if "scrollTop()"" is more than 0) if($(window).scrollTop() > 0){ // If it's more than or equal to 0, show the toTop button. console.log("is more"); $("#toTop").fadeIn("slow"); } else { // If it's less than 0 (at the top), hide the toTop button. console.log("is less"); $("#toTop").fadeOut("slow"); } } }); // When the user clicks the toTop button, we want the page to scroll to the top. $("#toTop").click(function(){ // Disable the default behaviour when a user clicks an empty anchor link. // (The page jumps to the top instead of // animating) event.preventDefault(); // Animate the scrolling motion. $("html, body").animate({ scrollTop:0 },"slow"); });
I hope I have commented the above code so you will understand what is happening. The demo html file also has comments in it to make it easier to understand. If something is not working properly or you think this is the best tutorial that’s ever been written, don’t hesitate to comment π
Thanks, my scroll is work more smooth then before.
Nice to hear that!
Great and helpful tutorial. I am using this , This is also simple
$(document).ready(function(e) {
var a = 400,
t = 1200,
l = 700,
s = e(“.scrool-top”);
e(window).scroll(function() {
e(this).scrollTop() > a ? s.addClass(“scrool-is-visible”) : s.removeClass(“scrool-is-visible scrool-fade-out”), e(this).scrollTop() > t && s.addClass(“scrool-fade-out”)
}), s.on(“click”, function(a) {
a.preventDefault(), e(“body,html”).animate({
scrollTop: 0
}, l)
})
})
Here is working demo
i had used scrollto min for my single page bootstrap website. but want to include one external link. while try to add that can’t able to click those links. please give some suggestions to add those external links on my page. reference link: http://vindia.net/demo/s5/
I stumbled upon this looking for a scroll to top code. The example works fine. The author just left out a final “});” to close out the document.ready function in the javascript code.
Thank you for pointing out the error in the code π I have fixed it now.
No problem, only 3 years late π
// Check weather the user has scrolled down (if βscrollTop()ββ is more than 300)
if($(window).scrollTop() > 300){
$(“#toTop”).fadeIn(“slow”);
}
// Check weather the user has scrolled down (if “scrollTop()”” is more than 0)
if($(window).scrollTop() > 300){
#back-top
{
display:none;
}
#back-top a
{
display:none;
}
$(document).ready(function(){
$(function(){
$(“window”).scroll(function(){
if($(“this”).scrollTop()>300)
{
$(“#back-top”).fadeIn();
}
else
$(“#back-top”).fadeOut();
});
$(“#back-top”).click(function(){
$(“this”).scrollTop(0);
});
});
});
This is awesome mate, thanks a lot.
Thank you for the snippet. When I put extra }); in bottom, it works fine.
But smooth scrolling won’t work. I jumps to the top immediately.
Okay, seems like it’s Firefox related problem.
No, you’re missing an event definition. The click function should be:
$('#toTop').click(function(event){
event.preventDefault();
$('html, body').animate({
scrollTop:0
},'slow');
});
Then it works, for me at least. Note defining “event” to be passed to the function.
I could not get the floating “go to top” to show up. I have a lot of other CSS & JS (localScroll too) so I used your example and dropped my stuff into it until I broke yours. So I don’t know why, but moving the page CSS paragraph #toTop to the beginning of the pages section fixed my problem.
really help me, thx!
Nice script Adrian!
What I immediately noticed is that one additional }); is missing at the end of the script, causing it to break. After adding it the script works perfectly in Chrome, IE and Safari.
Then there is still one problem concerning Firefox. The event.preventDefault(); causes the “smooth scrolling” function to not be smooth anymore. Just remove this line, and replace the <a href='#' part in your HTML with <a href='javascript:void(0)' to prevent other empty links to trigger the scroll function. It should now work across all major browsers.
Thank You sir!
The solution You provided:
*removing the “event.preventDefault();” line AND
* writing <a href='javascript:void(0)' instead of regular link,
helped me alot!
Thanks again π
very informative. Thanks.
Just take look into this example http://www.etechpulse.com/2014/05/jquery-scroll-to-top-button-onclick-css.html
Love this script! But I got a problem.. I copy the codes and everything. But the jQuery doesn’t work. When I click on the link “back to top” it just jumps right back ut. The scroll/slide doesn’t happen, just a jump like u usually go to page. I tried the test with “alert(“jQuery is working!”);” and that work and showed up. What am I doing wrong?! Also tried the script to “Scrollto” and got the same problem there.. Totally a newbie at jquery.
Hope u understand my crapy explanation!
Thanks for sharing this !!!!!
Now my scroll is running perfectly and smoothly .
Hello,
looks like there is an issue with Firefox (current version I’m using is 26.0)
While this page (your tutorial text page)
http://adriantomic.se/development/scroll-to-the-top-with-jquery/
scrolls smoothly to the top
the demo page
http://adriantomic.se/scrolltotop
doesn’t scroll, instead it bumps to top.
Maybe you’d think to rewite/modify your tutorial to make it coherent with your article page π and allow a more effective cross-browser compatibility
Anyway, thank you for the guide,
Robert
Thanks for this. I couldn’t get it to work in FireFox but it works in Chrome. Also the script on this page did not work for me but I had to view the source in Firebug and used that script and it worked. Thanks again.
Having read this I thought it was really enlightening.
I appreciate you spending some time and effort to put this content
together. I once again find myself personally spending way too
much time both reading and commenting. But so what, it was still worth it!
Thank you π I’m glad you found my post helpful. Cheers!
Can all of this code be put into an external javascript folder? If so, is there any additional code needed in the html to call it?
Yes it is possible to put the code in a separate javascript file.
1. Copy all the code below and paste it into a text file. Save it as scrolltotop.js in the same folder as your html file.
$(document).ready(function()
{
// Hide the toTop button when the page loads.
$("#toTop").css("display", "none");
// This function runs every time the user scrolls the page.
$(window).scroll(function(){
// Check weather the user has scrolled down (if "scrollTop()"" is more than 0)
if($(window).scrollTop() > 0){
// If it's more than or equal to 0, show the toTop button.
console.log("is more");
$("#toTop").fadeIn("slow");
}
else {
// If it's less than 0 (at the top), hide the toTop button.
console.log("is less");
$("#toTop").fadeOut("slow");
}
});
// When the user clicks the toTop button, we want the page to scroll to the top.
$("#toTop").click(function(){
// Disable the default behaviour when a user clicks an empty anchor link.
// (The page jumps to the top instead of // animating)
event.preventDefault();
// Animate the scrolling motion.
$("html, body").animate({
scrollTop:0
},"slow");
});
2. In your header of your html document. Write the code below:
3. Save and refresh view the html in a browser.
you have to define div in html with id =”toTop”
like this
Go to Top
or put this(Go to Top) code in any div