Menu

Brandon Rome

web, optimal, and things

Simple jQuery Smooth Scroll with Scroll to Top

This came up while working on a little one-page site for a customer.

After some digging, I found a few snippits that combined to make this a rather pain-free process. It’s not flashy, and I’m sure there are 100 ways to do it better, but this worked for me.

First, the jQuery:

[javascript]
$(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();
}
});
[/javascript]

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. I may look in to that later.

z-60pxoffset

The related HTML:

[html]
<div class="bottomMenu"><a href="#top"><span>Back to Top</span></a></div>
[/html]

And lastly,the CSS:

[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;
}
[/css]

Sources:

Leave a Reply