Newer
Older
pre-www / build / assets / js / blocks / secondary-nav.js
window.addEventListener('load', (event) => {
    
    let currentScrollPos = 0
    let prevScrollPos = 0

    const secondaryNav = document.querySelector('.secondary-nav')

    if (typeof(secondaryNav) == 'undefined' || secondaryNav == null) return

    const secondaryNavTrigger = document.querySelector('.secondary-nav-trigger')
    const secondaryNavLinks = secondaryNav.querySelectorAll('ul li a')

    function getSecondaryNavHeight(){
        document.documentElement.style.setProperty("--secondary-nav-height", `${secondaryNav.clientHeight}px`)
    }

    if(secondaryNav !== null) getSecondaryNavHeight()

    let secondaryNavObserver = new IntersectionObserver((entries) => { 
        entries.forEach(entry => {
            if(!entry.isIntersecting && currentScrollPos > entry.target.getBoundingClientRect().top){
                secondaryNav.classList.add('is-visible')
            } else {
                secondaryNav.classList.remove('is-visible')
            }
        })
    }, 
    {
        threshold: 1,
        rootMargin: '-1px 0px 0px 0px'
    })

    function getSecondaryNavButtonWidth(){
        const secondaryNavButtonWidth = secondaryNav.querySelector('.secondary-nav__btn').clientWidth
        secondaryNav.style.setProperty("--secondary-nav-button-width", `${secondaryNavButtonWidth}px`)
    }
    if(secondaryNav !== null) {

        secondaryNavObserver.observe(secondaryNavTrigger)

        getSecondaryNavButtonWidth()

        window.addEventListener('scroll', () => {
            currentScrollPos = window.scrollY
            if (prevScrollPos > 0 && prevScrollPos < currentScrollPos && currentScrollPos > window.innerHeight ) {
                secondaryNav.classList.remove('is-stacked')
            } else if (prevScrollPos >= currentScrollPos) {
                secondaryNav.classList.add('is-stacked')
            }
            prevScrollPos = currentScrollPos
        })
    }

    window.addEventListener('resize', function(){
        if(secondaryNav !== null) {
            getSecondaryNavButtonWidth()
        }
    })

    //smooth scrolling anchor links
    secondaryNavLinks.forEach(link => {
        link.addEventListener('click', function(e){
            e.preventDefault()
            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            })
        })  
    })

})