A simple animated Back to Top button using jQuery


In lengthy web pages, it is more sensible to have a 'Back to top' button, instead of making the user scroll all the way up again. Below is the code for a simple floating 'Back to top' button using jQuery. You can add an image or you can define a div and style it, and give it the "back-to-top" class.

You can also define the duration in milliseconds in which the page goes to the top and the offset of the document on which the button should appear (and disappear).

HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button onclick="href='#'"  class="back-to-top">Back to Top</button>

JAVASCRIPT:

<script type="text/javascript">
            // Code to provide functionality for the 'Back to Top' button
            jQuery(document).ready(function () {
                var offset = 220;
                var duration = 500;
                jQuery(window).scroll(function () {
                    if (jQuery(this).scrollTop() > offset) {
                        jQuery('.back-to-top').fadeIn(duration);
                    } else {
                        jQuery('.back-to-top').fadeOut(duration);
                    }
                });

                jQuery('.back-to-top').click(function (event) {
                    event.preventDefault();
                    jQuery('html, body').animate({ scrollTop: 0 }, duration);
                    return false;
                })
            });
        </script>

CSS:

.back-to-top {
   position: fixed;
   bottom: 2em;
   right: 0px;
   text-decoration: none;
   color: #000000; 
   background-color: rgba(235, 235, 235, 0.80);
   font-size: 12px;
   padding: 1em; 
   display: none; 
}

 .back-to-top:hover { 
   background-color: rgba(135, 135, 135, 0.50); 
}

0 comments:

Post a Comment