Skip to content

Instantly share code, notes, and snippets.

@dhruvangg
Last active May 29, 2020 07:50
Show Gist options
  • Save dhruvangg/e36ab5db3e3dace0e3097ed98dfcb1a0 to your computer and use it in GitHub Desktop.
Save dhruvangg/e36ab5db3e3dace0e3097ed98dfcb1a0 to your computer and use it in GitHub Desktop.
Check Element is in Viewport or not
$.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));
};
$(document).ready(function(){
$(window).scroll(function(){
if ($('#inViewport').isOnScreen()) {
// The element is visible, do something
alert("in viewport!");
} else {
// The element is NOT visible, do something else
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment