You may have seen a back to top link from sites you have visited and may wonder how they create that navigation. In this tutorial, I will show you step by step to create the this handy link. Firstly, we need to place a div contains the navigation link, in this particular example, we will have an arrow navigation in circle shape located at the right bottom position. You can place the following code inside the body page, it can place after the body or at the very end of the code. Remember that it should be placed under a parent which does not have a position relative on it. So, to be safe, place it inside the body html tag.
<div id="top-navigator"><div id="arrow-up"></div></div>
Once it has been placed, it is time to create css for the div object. One of the important style of this css is the position fixed property. This will make sure the object back to top link stay in fixed position. You will see that I apply 3% to the bottom and right position. You can change this to another values if you prefer. I would recommend to use percentage rather than px, rem, etc. Another style is the z-index value, make sure this number is the highest number represents on your css files, as this is going to be sitting on the top of your page content. And last important part is the display:none property. This makes the navigation by default hidden until a scrolling of the page exists.
#top-navigator{ position:fixed; right:3%; bottom:3%; text-align:center; border-radius:100%; background:#010211; width:30px; height:30px; padding:6px; font-size:1.5rem; opacity:.8; z-index:99999; cursor:pointer; display:none; } #top-navigator:hover{ opacity:.9; } #arrow-up{ width:0; height:0; border-left:12px solid transparent; border-right:12px solid transparent; border-bottom:12px solid #fff; font-size:0; line-height:0; margin:0 auto; display:inline-block; }
One of the amazing from the css is you can easily create an top arrow by using combination of the border positions. Looks great right? Don't have to use an image. If you prefer to use an image, simply add an image inside the div and you can remove the style for #arrow-up.
The last part of the important work is to include the JQuery script and add some javascript to trigger the event when the scrolling is happening. Please see below code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(window).scroll(function () { if ($(this).scrollTop()) { $('#top-navigator:hidden').stop(true, true).fadeIn(); } else { $('#top-navigator').stop(true, true).fadeOut(); } }); $("#top-navigator").click(function () { $('html, body').animate({ scrollTop: $('html').offset().top }, 1000); }); </script>
Hope this tutorial helps and you can see directly the action on our site. If you see there is a long content, the back to top navigation should appears on the bottom right of the browser.