In a complex web application, I have to check whether certain HTML elements are visible partly/completely on the screen.
There are various reasons why certain elements are not visible on the screen:
- They have certain attributes, like display:none visibility:hidden width:0 height:0 opacity:0 and maybe others.
- Other elements are in front of the element.
- They are outside the parent's visible scroll area.
- To a certain extent, some of their parents have one or more of the properties above (elements with absolute or fixed positioning break the chain).
- They are outside the parent's visible area for other reasons, for instance the parent may be partly overlaid by other elements and they are only covering that part.
The things I found on stack overflow (like How to Check if element is visible after scrolling?, http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport and others) are doing simple checks for one or two of the reasons above, but do not even nearly try to detect all reasons I lined out.
Before I now start implementing everything manually, including all the corner cases: Is there a reason-agnostic check available through javascript, that will give me feedback on whether the element is visible in the rendered result?
For now, the easiest and most reliable thing I could come up with was the idea (didn't test it yet) to modify the background-color attribute of the element, use the html2canvas library before and after, and check whether the resulting images match.
Is there anything short of that "workaround"?
(Update: I have tested my html2canvas approach and not only is it slow, it also gives false positives because the images are not always the same, even if the element with changed background-color is not visible at all.)