Skip to content

Instantly share code, notes, and snippets.

@luke-rmaki
Last active October 5, 2018 10:17
Show Gist options
  • Save luke-rmaki/1149b3d2496f7c34da80b7ee9bd7a368 to your computer and use it in GitHub Desktop.
Save luke-rmaki/1149b3d2496f7c34da80b7ee9bd7a368 to your computer and use it in GitHub Desktop.
Function to see if element is in viewport
function elementInView(target) {
// selects target div
const targetDiv = document.querySelector(target);
// gets target position from top of viewport
const targetPosition = targetDiv.getBoundingClientRect();
switch (true) {
case targetPosition.top > 1:
console.log('hidden');
break;
case targetPosition.top <= 0 && targetPosition.bottom >= 0:
console.log('visible');
break;
case targetPosition.bottom < 0:
console.log('hidden');
break;
default:
break;
}
}
// add function to document.addEventListener('scroll')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment