Skip to content

Instantly share code, notes, and snippets.

@soyuka
Last active December 17, 2015 08:49
Show Gist options
  • Select an option

  • Save soyuka/5582995 to your computer and use it in GitHub Desktop.

Select an option

Save soyuka/5582995 to your computer and use it in GitHub Desktop.
Smooth Scroll To from link hash in a defined container especially done for OnePage websites.
/*
Use example :
$('a[href^="#"]').SmoothScrollTo('slow', 'container');
or
$('a[href^="#"]').SmoothScrollTo();
A margin is automaticaly taken from the container padding-top.
*/
(function($) {
var methods = {
init: function (settings) {
settings = $.extend( {
'speed' : 'slow',
'container' : navigator.userAgent.match('Chrome') ? 'body' : 'html'
}, settings);
var topMargin = parseInt($(settings.container).css('padding-top'));
return this.each( function() {
$(this).on('click', function(e) {
e.preventDefault();
methods.jumpTo(
$(this).attr("href")
, $(settings.container)
, topMargin
, settings.speed
);
});
});
},
jumpTo: function(hash, $container, topMargin, speed) {
var regex = new RegExp("(.*)\#(.*)","gi");
 
//&& hash != location.hash => prevents redo
if ( hash.match("\#(.+)") ) {
hash = hash.replace(regex,"$2");
if ( $('#'+hash).length > 0 ) {
var scroll = $('#'+hash).position().top - topMargin;
$container.animate( {
scrollTop: scroll
},
speed,
function() {
if(history.pushState) {
history.pushState(null, null, '#'+hash);
}
else {
location.hash = '#'+hash;
}
});
}
}
},
//Just used for window load event, can be easily removed.
load: function(settings) {
settings = $.extend( {
'speed' : 'slow',
'container' : navigator.userAgent.match('Chrome') ? 'body' : 'html'
}, settings);
var topMargin = parseInt($(settings.container).css('padding-top')),
$container = $(settings.container);
if ( location.hash != undefined && $(location.hash).length > 0) {
//Check if the scroll is near the hash so scrolling is not needed
var nearTo = ( ($(location.hash).position().top - topMargin) / $container.scrollTop() );
//1 is right on it
if(nearTo > 1.5 || nearTo < 0.95) {
var scroll = $(location.hash).position().top - topMargin;
$container.animate({ scrollTop: scroll }, settings.speed);
}
}
return false;
}
};
$.fn.SmoothScrollTo = function() {
return methods.init.apply( this, arguments );
};
 
// Load slide on window load
$(window).load(function() {
return methods.load.apply( this, arguments );
});
 
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment