Created
April 18, 2019 14:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const addClass = (elem, className) => { | |
elem.classList.add(className) | |
} | |
export const removeClass = (elem, className) => { | |
elem.classList.remove(className) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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