Skip to content

Instantly share code, notes, and snippets.

@adamdehaven
Created September 25, 2017 17:57
Show Gist options
  • Save adamdehaven/8acc0525389027460ac1cd3ac8b376a2 to your computer and use it in GitHub Desktop.
Save adamdehaven/8acc0525389027460ac1cd3ac8b376a2 to your computer and use it in GitHub Desktop.
jQuery function to detect if element is within viewport
// If element is in viewport
// EXAMPLE: $('.element').isOnScreen();
$.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 bounds = this.offset();
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));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment