Just a few snippits that combined to make a simple jQuery smooth scroll, scroll to top feature.
It’s not flashy, and I’m sure there are 100 ways to do it better, but this worked for me.
jQuery
$(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({scrollTop: target.offset().top -60}, 1000); return false; } } }); }); $(document).scroll(function () { var y = $(this).scrollTop(); if (y > 500) { $('.bottomMenu').fadeIn(); } else { $('.bottomMenu').fadeOut(); } });
Note the line that reads scrollTop: target-offset().top -60. In this situation, the customer had a large margin above the in-line linked headers. Fine tune this number as needed, or simply set -60 to 0 to remove the padding. Furthermore, and without any testing, this may have been avoidable by applying padding to the top of these in-line links.
HTML
<div class="bottomMenu"><a href="#top"><span>Back to Top</span></a></div>
CSS
.bottomMenu { position: fixed; bottom: 15px; right:15px; z-index: 100; } .bottomMenu a { background-image:url('../images/top.png'); background-repeat:no-repeat; width:60px; height:60px; display:block; } .bottomMenu a span { display:none; }
Sources: