javascriptjqueryzk

How to check if an element is off-screen


I need to check with jQuery if a DIV element is not falling off-screen. The elements are visible and displayed according CSS attributes, but they could be intentionally placed off-screen by:

position: absolute; 
left: -1000px; 
top: -1000px;

I could not use the jQuery :visible selector as the element has a non-zero height and width.

I am not doing anything fancy. This absolute position placement is the way my Ajax framework implements the hide/show of some widgets.


Solution

  • Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?

    Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):

    jQuery.expr.filters.offscreen = function(el) {
      var rect = el.getBoundingClientRect();
      return (
               (rect.x + rect.width) < 0 
                 || (rect.y + rect.height) < 0
                 || (rect.x > window.innerWidth || rect.y > window.innerHeight)
             );
    };
    

    You could then use that in several ways:

    // returns all elements that are offscreen
    $(':offscreen');
    
    // boolean returned if element is offscreen
    $('div').is(':offscreen');