Skip to content

Instantly share code, notes, and snippets.

@airarm
Created November 30, 2023 13:01
Show Gist options
  • Save airarm/bf156e677d3d6f0a8ad02e88b3d74523 to your computer and use it in GitHub Desktop.
Save airarm/bf156e677d3d6f0a8ad02e88b3d74523 to your computer and use it in GitHub Desktop.
if(location.hash) {
window.scrollTo(0, 0);
}
const scrollToElement = (element) => {
const elementRect = element.getBoundingClientRect();
let elementTop = elementRect.top + window.scrollY;
window.scroll({
behavior: 'smooth',
top: elementTop
});
}
window.addEventListener('DOMContentLoaded', () => {
if(location.hash)
{
let findElementByHash = document.getElementById(location.hash.replace('#', ''));
if(findElementByHash){
scrollToElement(findElementByHash);
}
}
document.querySelectorAll('a')?.forEach(item => {
let href = item.getAttribute('href');
if(href && href.match(/^#.+/))
{
item.addEventListener('click', e => {
e.preventDefault();
const target = e.currentTarget || e.target;
const href = target.getAttribute('href');
let findElementByHash = document.getElementById(href.replace('#', ''));
if(findElementByHash){
scrollToElement(findElementByHash);
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment