Is it possible to determine if an html element is visible to the user?
A page has an input field with a datepicker. If the user clicks on the input
I tried a different approach using elements coordinates (getBoundingClientRect
) and then using elementFromPoint
to see if the element is hidden or visible.
DEMO (Follow the instruction on the right side)
var rectPos = this.getBoundingClientRect();
var result = 0;
if (this == document.elementFromPoint(rectPos.left,
rectPos.top)) {
result++;
}
if (this == document.elementFromPoint(rectPos.left,
rectPos.bottom - 1)) {
result++;
}
if (this == document.elementFromPoint(rectPos.right - 1,
rectPos.top)) {
result++;
}
if (this == document.elementFromPoint(rectPos.right - 1, rectPos.bottom - 1)) {
result++;
}
if (result == 4) {
result = 'visible';
} else if (result == 0) {
result = 'hidden';
} else {
result = 'partially visible';
}
Further Readings: getBoundingClientRect, elementFromPoint