HTML: Is there a way to determine if an element is behind another element?

We have an application with a search popup. You search for a term, and it finds them on the page and adds a class to the word, which in turn highlights the text. Sometimes the found instance is located in the page area, which is located behind the search popup. If so, I would like to change the opacity of the search popup so that the user can see the instance behind it. Is there an easy way to do this? Any tips or tricks are welcome. One of the requirements is that the search popup remains open after the search, so we cannot just close / hide it.

+4
source share
2 answers

You can use getBoundingClientRect() for the found text and popup and compare the sizes.

MSDN
MDN range , element

You can act directly in text ranges, but it looks like you have an element that wraps the found text to apply the selection, so I would just use this element. I think you can just pass your found text and a popup for this function to check if they overlap:

 function isOverlapping (a, b) { var rectA = a.getBoundingClientRect(); var rectB = b.getBoundingClientRect(); return rectA.top < rectB.bottom && rectA.bottom > rectB.top && rectA.left < rectB.right && rectA.right > rectB.left; } 

Edit: I must have too much time on my hands, because here is a fun demo: http://jsfiddle.net/gilly3/qUFLJ/4/

+3
source

Yes, using JavaScript would be easy. Since you know if the popup is open, I assume you know its width and position. Just create a bounding box and check if this element is in this field. getBoundingClientRect is useful for this. If you use jQuery, offset can also help you.

Let me know if you need an example.

0
source

All Articles