Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Smooth scroll to #hash links with and without offset
// 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
}
}
// 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'
});
}
}
@webregie
Copy link

webregie commented Nov 19, 2020

Perhaps there is a problem with Mac and Safari... but thank you for this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment