Created
September 25, 2017 17:57
-
-
Save adamdehaven/8acc0525389027460ac1cd3ac8b376a2 to your computer and use it in GitHub Desktop.
jQuery function to detect if element is within viewport
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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