Last active
July 15, 2016 19:23
-
-
Save raddevon/8958307 to your computer and use it in GitHub Desktop.
Anchor target fix for fixed navbar. Based on http://stackoverflow.com/a/13067009/800492 but with additions to avoid colliding with Bootstrap's JS widgets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Creates an attribute pseudo-selector allowing for wildcards | |
jQuery.expr.pseudos.attr = $.expr.createPseudo(function(arg) { | |
var regexp = new RegExp(arg); | |
return function(elem) { | |
for(var i = 0; i < elem.attributes.length; i++) { | |
var attr = elem.attributes[i]; | |
if(regexp.test(attr.name)) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
}); | |
// Correctly targets anchors accounting for fixed navbar | |
/** | |
* Check a href for an anchor. If exists, and in document, scroll to it. | |
* If href argument ommited, assumes context (this) is HTML Element, | |
* which will be the case when invoked by jQuery after an event | |
*/ | |
function scrollIfAnchor(href) { | |
if (matchMedia('only screen and (min-width: 980px)').matches) { | |
href = typeof(href) == "string" ? href : $(this).attr("href"); | |
// You could easily calculate this dynamically if you prefer | |
var fromTop = 62; | |
// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo) | |
// Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174 | |
// Also ensures the link clicked does not have a data attribute to avoid breaking | |
// Bootstrap JS components. Checks if this is the window to allow scrolling on fresh | |
// load despite window's data attribute. | |
if(href.indexOf("#") == 0 && !$(this).is(":attr('^data-')")) { | |
var $target = $(href); | |
// Older browser without pushState might flicker here, as they momentarily | |
// jump to the wrong position (IE < 10) | |
if($target.length) { | |
$('html, body').animate({ scrollTop: $target.offset().top - fromTop }); | |
if(history && "pushState" in history) { | |
history.pushState({}, document.title, window.location.pathname + href); | |
return false; | |
} | |
} | |
} | |
} | |
} | |
// Runs on page load | |
scrollIfAnchor(window.location.hash); | |
// Intercept all anchor clicks | |
$("body").on("click", "a", scrolIfAnchor); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment