jqueryhtmlvisibility

Determine visibility / real z-index of html elements


Is it possible to determine if an html element is visible to the user?

Example

A page has an input field with a datepicker. If the user clicks on the input field, another div appears which allows the user to select the desired date.

As long the datepicker is visible it hides elements which are behind it. I need a way to tell if an element is hidden or not.

First Approach

One way would be to check and compare the z-index values. But if they are note explicitly set, they are always auto.

Another way could be a way to check if an element is visible to the user. But i can't think of any way to do so.

The :visible selector does not work in this situation, because the element is only hidden to the user's eyes but still visible.

Any suggestions?


Solution

  • This might work. I haven't tested it. It's a modified version of some code I found here.

    function elementWithinElement(elemPossiblyCovered, elemPossiblyCovering)
    {
        var top = elemPossiblyCovered.offsetTop;
        var left = elemPossiblyCovered.offsetLeft;
        var width = elemPossiblyCovered.offsetWidth;
        var height = elemPossiblyCovered.offsetHeight;
    
        while (elemPossiblyCovered.offsetParent)
        {
            elemPossiblyCovered = elemPossiblyCovered.offsetParent;
            top += elemPossiblyCovered.offsetTop;
            left += elemPossiblyCovered.offsetLeft;
        }
    
        return (
        top >= elemPossiblyCovering.offsetTop &&
        left >= elemPossiblyCovering.offsetLeft &&
        (top + height) <= (elemPossiblyCovering.offsetTop + elemPossiblyCovering.offsetHeight) &&
        (left + width) <= (elemPossiblyCovering.offsetLeft + elemPossiblyCovering.offsetWidth)
      );
    }
    

    So it'd be something like:

    if(elementWithinElement(myTextbox, theDatepickerDiv))
    { 
        // It's hidden
    }else
    {
        //It's visible
    }
    

    Edit: Some of the code wasn't updated. Should be fixed now.

    Edit Again: Fixed the code and tested it. It works!