Last active
May 9, 2018 21:23
-
-
Save iansvo/55b55940f43a2a2d950462458e1441d4 to your computer and use it in GitHub Desktop.
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
// Check if element is visible, above, or below the viewport | |
function canYouSeeMe(selector, debug) | |
{ | |
var $target = selector; | |
if( typeof selector === 'string' ) { | |
$target = document.querySelector(selector); | |
} | |
// Bail if our target element doesn't exist | |
if( !$target ) return; | |
// Get Element Top & Height to get range | |
var offset = $target.offsetTop + $target.offsetHeight; | |
var output = { | |
element: $target, | |
above: false, | |
below: false, | |
visible: false | |
}; | |
// Begin visibility checks | |
if( window.pageYOffset + window.innerHeight < $target.offsetTop ) | |
{ | |
if( debug ) console.log('element below viewport'); | |
output.below = true; | |
output.above = false; | |
} | |
else if( window.pageYOffset > offset) | |
{ | |
if( debug ) console.log('element above viewport'); | |
output.below = false; | |
output.above = true; | |
} | |
else | |
{ | |
if( debug ) console.log('element visible'); | |
output.below = false; | |
output.above = false; | |
output.visible = true; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment