I'm wondering if anyone has an easy solution for this. I'm trying to detect if any part of a HTML
element finds itself outside of the viewport. I've tried utilizing the following code:
$.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();
Brought to you by Steven
I can only get this to work when the entire element is not viewable anymore, but I just need to know if part of the element is outside of the viewport.
When the element is outside of the viewport, then I'm putting a different class on it, so that it will shift to the left instead so that it is viewable again.
Something like:
if(elementIsPartiallyOutsideViewport) {
ele.addClass('move-left');
}
Any ideas?
Most of the browsers already support getBoundingClientRect()
method. So you can try the following code.
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
You simply pass the element to the function and get false
if element is not inside the viewport.
Usage.
if (!isElementInViewport(el)) {
el.addClass('move-left');
}
Edit
Just an addition. You can get more info about getBoundingClientRect()
function and the browser support in here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With