Skip to content

Instantly share code, notes, and snippets.

@deryckoe
Created June 5, 2019 19:08
Show Gist options
  • Save deryckoe/24bdd303c5508d8ce7a6448fc6a6ae96 to your computer and use it in GitHub Desktop.
Save deryckoe/24bdd303c5508d8ce7a6448fc6a6ae96 to your computer and use it in GitHub Desktop.
Calculate wich element has more vertical space visible on viewport
Brain juices all over the const sectionElement = document.querySelectorAll('.section');
if (sectionElement) {
const onEvents = ['scroll', 'resize', 'load'];
onEvents.forEach((event) => {
window.addEventListener(event, function () {
const sectionHeights = [];
sectionElement.forEach((item) => {
let box = item.getBoundingClientRect();
let docHeight = window.innerHeight || document.documentElement.clientHeight;
let { topOffset, viewHeight, maxHeight } = 0;
if (box.top <= box.height) {
topOffset = Math.abs(box.top);
viewHeight = box.height - topOffset;
maxHeight = viewHeight <= docHeight ? viewHeight : docHeight;
item.dataset.viewHeight = String(maxHeight);
}
sectionHeights.push(viewHeight || 0);
});
let elementIndex = sectionHeights.indexOf(Math.max(...sectionHeights));
sectionElement.forEach((item, index) => {
if ( index === elementIndex ) {
item.classList.add('is-active');
} else {
item.classList.remove('is-active');
}
})
});
})
}place
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment