Dynamic Back to Top Button Using Jquery

Dynamic Back to Top Button Using Jquery:-Whenever you are reading a long post or an article which have a good amount of content then need to scroll up to the top to get the menu options. It is easy to fix if you have fixed menu or you can add a back to top button.

If we think about it, we just need a link at the bottom of every post that will help us to reach direct to top.  By using simple HTML you can ad simple back to top link using the below one line code.

<a href=”#” class=”back-to-top”>Back to Top</a>

After that just need to style and setup position for the back to top button using jquery . Here we maintain its position fixed and moving it to bottom right side of the screen. To make the button stand out give it a transparent background and hover effect.

Jquery:-

First of all we must have to add jQuery to our page, this can be done through adding this script to your page

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js”></script>

If you are working on WordPress or similar platform then you can use add_action & wp_enqueue_script

The main jQuery function is quite simple, but first we have to set our offset that means after how much scrolling the button should be appear in the bottom & how long we need the scroll to top effect to last. We don’t have to setup it for too fast but not also slow because that will be annoying.

Then we need to make the button visible when the visitor scrolls. To do this you need to use jQuery scroll function. In this function we have to fetch the current scroll position using scroll top. Check if it is more than offset and then we show the button using fadeIn function or if it is less than offset value then we use fadeout function.

For the scroll to top option we have to intercept click event on button. First we have to block the default clicks being triggered. And then we scroll back to top using animate function, passing in the duration. And after this we return false to assure that no other events are raised after it.