Last active
October 29, 2017 17:45
-
-
Save CITguy/bcaed6b90406f68ac44afeed3c1e6949 to your computer and use it in GitHub Desktop.
Use vanilla JavaScript to fix in-page anchors when using <base>
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
(function () { | |
var hashAnchors = document.querySelectorAll('a[href^="#"]'); | |
/* | |
Legacy browsers don't support NodeList.prototype.forEach, | |
so we have to call Array.prototype.forEach setting the | |
context to the NodeList. | |
*/ | |
[].forEach.call(hashAnchors, function (anchor) { | |
anchor.addEventListener('click', function (event) { | |
event.preventDefault(); | |
/* | |
Browsers support setting location.hash as a string | |
with or without the starting "#". | |
This works best when the <a> element only contains text. | |
Otherwise, "event.target" may not be the <a> element. | |
*/ | |
document.location.hash = event.target.getAttribute('href'); | |
}); | |
}); | |
})(); |
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
( _ => { | |
let hashAnchors = document.querySelectorAll('a[href^="#"]'); | |
/* | |
If your browser supports ES6, it likely supports NodeList.prototype.forEach (no IE). | |
https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Browser_Compatibility | |
*/ | |
hashAnchors.forEach( anchor => { | |
anchor.addEventListener('click', evt => { | |
evt.preventDefault(); | |
document.location.hash = evt.target.getAttribute('href'); | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment