Smooth Scrolling for anchor links

If you’re linking to an anchor link on a page, a smooth scroll is a nice touch. Without this the browser will jump straight there.

// Smooth scrolling anchor links
function ea_scroll( hash ) {
var target = $( hash );
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
var top_offset = 0;
if ( $('.site-header').css('position') == 'fixed' ) {
top_offset = $('.site-header').height();
}
if( $('body').hasClass('admin-bar') ) {
top_offset = top_offset + $('#wpadminbar').height();
}
$('html,body').animate({
scrollTop: target.offset().top - top_offset
}, 1000);
return false;
}
}
// -- Smooth scroll on pageload
if( window.location.hash ) {
ea_scroll( window.location.hash );
}
// -- Smooth scroll on click
$('a[href*="#"]:not([href="#"]):not(.no-scroll)').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') || location.hostname == this.hostname) {
ea_scroll( this.hash );
}
});
view raw global.js hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk