Skip to content

Instantly share code, notes, and snippets.

@atikju
Last active October 11, 2018 21:17
Show Gist options
  • Save atikju/e087e797a149701548c3bb375e5a5f34 to your computer and use it in GitHub Desktop.
Save atikju/e087e797a149701548c3bb375e5a5f34 to your computer and use it in GitHub Desktop.
//this script requires jQuery
function isVisibleOnScreen(target){
var depth = $(target).offset().top; //depth from the top
var targetHeight = $(target).height(); //height of the target element
var winHeight = $(window).height(); //current window height
var totalTargetDepth = parseInt(targetHeight)+parseInt(depth)+winHeight; //total depth
var scrolledDepth = $(window).scrollTop(); //how far you scrolled
var elmVisible = winHeight+scrolledDepth; //the point where the target starts displaying at the bottom of the screen
//console.log(scrolledDepth+'-'+elmVisible+'-'+depth);
//runs the logic condition
if(elmVisible >= depth && elmVisible < totalTargetDepth){
return true;
}else{
return false;
}
}
//usage
var myTarget = $('.selector'); //grab the selector
//use it..
if(isVisibleOnScreen(myTarget) == true){
console.log('Visible On Screen');
}else{
console.log('Not visible on screen');
}
//Enjoy!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment