Last active
May 29, 2020 07:50
-
-
Save dhruvangg/e36ab5db3e3dace0e3097ed98dfcb1a0 to your computer and use it in GitHub Desktop.
Check Element is in Viewport or not
This file contains 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
$.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