Site logo

Archived topic

Body class on active sticky navigation?

3 replies · Started by Christian on August 31, 2022

Viewing posts 1–4 of 4

Hi there!

I am currently wondering if there is any way to have a CSS class on the body when the sticky navigation is active? I can see that the nav element itself is changing classes but for some other styling I would love to have a class on the body element too. Any ideas how to achieve this? 🤔

Thanks in advance!
Chris

Hi there,

you can use the Javascript MutationObserver to watch the navigation for an ID change and when it does tack on your body class.

Try this in a wp_footer hook:

<script>
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 class 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)
</script>

Perfect, thank you David – this works like a charm!

Awesome - glad to hear that !

This archived topic is closed to new replies.