Checking if a div is visible within viewport using jquery
Here is the working versions: http://jsfiddle.net/wN7ah/455/
Function that does the magic:
$.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));
};
Usage:
$(window).scroll(function() {
if ($('.orange').isOnScreen() == true) {
//alert("removing orange");
$('.orange').remove();
}
if ($('.red').isOnScreen() == true) {
//alert("removing red");
$('.red').remove();
}
});
If any orange or red is present in onscreen it'll remove them.
If you want to check when it's removed, add alert before removing: http://jsfiddle.net/wN7ah/457/