Created
November 30, 2023 13:01
-
-
Save airarm/bf156e677d3d6f0a8ad02e88b3d74523 to your computer and use it in GitHub Desktop.
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
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