Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if DOM element is partially out of the viewport

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?

like image 480
Romes Avatar asked Feb 10 '14 21:02

Romes


1 Answers

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

like image 143
Zafar Avatar answered Sep 28 '22 16:09

Zafar