[Resolved] Body class on active sticky navigation?

Home Forums Support [Resolved] Body class on active sticky navigation?

Home Forums Support Body class on active sticky navigation?

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2329384
    Christian

    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

    #2329431
    David
    Staff
    Customer Support

    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>
    #2329450
    Christian

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

    #2329455
    David
    Staff
    Customer Support

    Awesome – glad to hear that !

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.