Skip to content

Instantly share code, notes, and snippets.

@berryp
Created September 21, 2013 20:49
Show Gist options
  • Select an option

  • Save berryp/6654043 to your computer and use it in GitHub Desktop.

Select an option

Save berryp/6654043 to your computer and use it in GitHub Desktop.
jQuery method to test if any part of a given element is visible in the viewport.
/**
* jQuery method to test if any part of a given element is visible in the viewport.
* Source: http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen
**/
$.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