Created
June 5, 2019 19:08
-
-
Save deryckoe/24bdd303c5508d8ce7a6448fc6a6ae96 to your computer and use it in GitHub Desktop.
Calculate wich element has more vertical space visible on viewport
This file contains 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
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