Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active April 29, 2017 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elhardoum/168f86ff1a037413eff877ab31137481 to your computer and use it in GitHub Desktop.
Save elhardoum/168f86ff1a037413eff877ab31137481 to your computer and use it in GitHub Desktop.
Adjust scroll when you have a fixed menu and a hash URL
var hashScrollFix = function() {
var hash = location.hash
, menu = $('.main-navi.fixed') // your fixed menu selector
, itm;
// I added menu.position().top >= 0 because I fade my menu to above viewport
// with a negative top position
if ( menu.is(':visible') && menu.position().top >= 0 ) {
itm = $(hash);
if ( !itm || !itm.offset() || !itm.offset().top )
return;
var jump = function() {
// adjust scroll
return $('body').scrollTop(itm.offset().top - menu.outerHeight());
}
// on load
jump();
// chances are we may need to jump again
setTimeout(jump, 100);
}
}
$(window).bind('hashchange', function() {
return hashScrollFix();
});
var makeMyMenuFixed = function() {
// .... do things that render a fixed menu
// then adjust scroll
// if you are using animation, then you might want to wait until it is done
// e.g .animate(.., .., hashScrollFix)
hashScrollFix();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment