1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| (function(document, history, location) { var HISTORY_SUPPORT = !!(history && history.pushState);
var anchorScrolls = { ANCHOR_REGEX: /^#[^ ]+$/, OFFSET_HEIGHT_PX: 50,
init: function() { this.scrollToCurrent(); window.addEventListener('hashchange', this.scrollToCurrent.bind(this)); document.body.addEventListener('click', this.delegateAnchors.bind(this)); },
getFixedOffset: function() { return this.OFFSET_HEIGHT_PX; },
scrollIfAnchor: function(href, pushToHistory) { var match, rect, anchorOffset;
if(!this.ANCHOR_REGEX.test(href)) { return false; }
match = document.getElementById(href.slice(1));
if(match) { rect = match.getBoundingClientRect(); anchorOffset = window.pageYOffset + rect.top - this.getFixedOffset(); window.scrollTo(window.pageXOffset, anchorOffset);
if(HISTORY_SUPPORT && pushToHistory) { history.pushState({}, document.title, location.pathname + href); } }
return !!match; },
scrollToCurrent: function() { this.scrollIfAnchor(window.location.hash); },
delegateAnchors: function(e) { var elem = e.target;
if( elem.nodeName === 'A' && this.scrollIfAnchor(elem.getAttribute('href'), true) ) { e.preventDefault(); } } };
window.addEventListener( 'DOMContentLoaded', anchorScrolls.init.bind(anchorScrolls) ); })(window.document, window.history, window.location);
|