Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Last active August 31, 2022 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diggeddy/0c2cea44e234cd3d620a93fdedb8788a to your computer and use it in GitHub Desktop.
Save diggeddy/0c2cea44e234cd3d620a93fdedb8788a to your computer and use it in GitHub Desktop.
Vanilla JS Sticky Nav Observer
const stickyNav = document.querySelector('#site-navigation')
const mutateOptions = {
attributes: true
}
function callback(mutationList, observer) {
mutationList.forEach(function(mutation) {
if (mutation.type === 'attributes' && mutation.attributeName === 'id') {
// handle ID change
if (mutation.target.id == 'sticky-navigation') {
document.body.classList.add("nav-is-sticky")
} else {
document.body.classList.remove("nav-is-sticky")
}
}
})
}
const observer = new MutationObserver(callback)
observer.observe(stickyNav, mutateOptions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment