Skip to content

Instantly share code, notes, and snippets.

@joedooley
Created April 18, 2019 14:41
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 joedooley/7886eea0199a2252b511c7e4b00db65a to your computer and use it in GitHub Desktop.
Save joedooley/7886eea0199a2252b511c7e4b00db65a to your computer and use it in GitHub Desktop.
Toggles class and sets dynamic header height on CSS variable. Uses Intersection Observer API to target the site headers next element sibling.
const addMarginTop = () => {
const siteHeader = document.querySelector('.site-header')
const siteHeaderHeight = window.getComputedStyle(siteHeader).getPropertyValue('height')
const siteHeaderSiblingEl = siteHeader.nextElementSibling
if (!siteHeader || !siteHeaderSiblingEl) {
return
}
siteHeaderSiblingEl.style.setProperty(`--header-height`, siteHeaderHeight)
}
export const load = () => {
addMarginTop()
window.onresize = () => {
addMarginTop()
}
if ('undefined' != typeof wp && 'undefined' != typeof wp.customize) {
wp.customize.bind('change', () => {
setTimeout(() => {
addMarginTop()
}, 1500)
})
}
}
export const addClass = (elem, className) => {
elem.classList.add(className)
}
export const removeClass = (elem, className) => {
elem.classList.remove(className)
}
import { addClass, removeClass } from './src/util/helpers'
import { load } from './src/components/header'
const SELECTOR = document.body
const ANIMATE_CLASS_NAME = 'animate'
const siteHeaderSiblingEl = document.querySelector('.site-header').nextElementSibling
const options = {
rootMargin: '0px',
threshold: 1.0,
}
const onIntersection = entries => {
entries.forEach(entry => {
const { isIntersecting } = entry
if (isIntersecting) {
removeClass(SELECTOR, ANIMATE_CLASS_NAME)
}
if (!isIntersecting) {
addClass(SELECTOR, ANIMATE_CLASS_NAME)
}
})
}
const init = () => {
const observer = new IntersectionObserver(onIntersection, options)
observer.observe(siteHeaderSiblingEl)
}
document.addEventListener(
'DOMContentLoaded',
() => init()
)
window.addEventListener(
'load',
() => load()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment