Skip to content

Instantly share code, notes, and snippets.

@jayllellis
Last active August 29, 2015 14:05
Show Gist options
  • Save jayllellis/a56f1a20263b9910bc2f to your computer and use it in GitHub Desktop.
Save jayllellis/a56f1a20263b9910bc2f to your computer and use it in GitHub Desktop.
jQuery check if element is on screen
/**
* @desc checks if current element is on screen or within viewport
* @param none
* @return int - the coordinates of the window vs. the element
*/
jQuery.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var elemtHeight = this.height()/2;// Get half of the height of current element
elemtHeight = Math.round(elemtHeight);// Round it to whole humber
var bounds = this.offset();// Coordinates of current element
bounds.top = bounds.top + elemtHeight;// Top is redefined as half of current element's height
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}
// Usage:
$(window).scroll(function(){
if( $('#my-div').isOnScreen() ){
// do something
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment