Last active
May 5, 2022 16:11
-
-
Save hsnyc/6fca8b5c237ff80a650674680e0be082 to your computer and use it in GitHub Desktop.
Smooth scroll to #hash links with and without offset
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
// Smooth Scroll to #links | with Off-Set ==================================== // | |
//get all # links in the document | |
let links = document.querySelectorAll('a[href*="#"]'); | |
// console.log(links); | |
//assign a click event to all the # links | |
for(let l = 0; l < links.length; l++) { | |
links[l].addEventListener('click', scrollMe, false); | |
} | |
function scrollMe(e) { | |
e.preventDefault(); //needed in order for the scroll to work | |
// get hash property | |
let hash = e.target.hash; | |
//check for empty hash | |
if(hash) { | |
// remove the # from the hash string | |
// so we can use it to reference the element by its ID. | |
let elemId = hash.replace('#', ''); | |
// Get Element we will be scrolling to | |
let element = document.getElementById(elemId); | |
// Set top off-set. Adjust as needed. | |
let headerOffset = 100; | |
// Get element's position relative to the viewport. | |
let elementPos = element.getBoundingClientRect().top; | |
// https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect | |
// Get final position we will scroll to | |
let offsetPos = elementPos + window.pageYOffset - headerOffset; | |
// https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset | |
// Scroll to that element | |
window.scrollTo({ | |
top: offsetPos, | |
behavior: 'smooth' | |
}); | |
// https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo | |
} | |
} |
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
// Smooth Scroll to #links | No offset ============================================= // | |
//get all # links in the document | |
var links = document.querySelectorAll('a[href*="#"]'); | |
//assign a click event to all the # links | |
for(var l = 0; l < links.length; l++) { | |
links[l].addEventListener('click', scrollMe, false); | |
} | |
function scrollMe(e) { | |
e.preventDefault(); //needed in order for the scroll to work | |
var hash = e.target.hash; | |
//check if hash is not empty | |
if(hash) { | |
// Scroll to that element | |
document.querySelector(hash).scrollIntoView({ | |
behavior: 'smooth' | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perhaps there is a problem with Mac and Safari... but thank you for this code.