2

I was wondering if there is any good way to check wether the texts of two html elements overlap? Carification: Checking for overlap between elements is no Problem I want to check wether the actual texts inside 2 Elements overlap.

Say I have the elements

<span id="green">Green is my cÔlor</span>
<span id="blue">blue is my color</span>

How could I check wether the texts of those 2 elements overlap? We can assume I have access to the jQuery Object of the given elements.

Edit: What I'm trying to say is that I can detect wether the borders of elements intercect, but in case of text there is the possibility that a good part of the space above and below each character is "unused".

Andy
  • 337
  • 1
  • 3
  • 14
  • "Checking for overlap between elements is no Problem I want to check wether the actual texts inside 2 Elements overlap" this statement is not entirely clear, it's confusing – Leo Feb 06 '15 at 08:50
  • http://stackoverflow.com/questions/5419134/how-to-detect-if-two-divs-touch-with-jquery – Deshan Feb 06 '15 at 08:52

2 Answers2

3
function getPositions(elem) {
    var clientRect = elem.getBoundingClientRect();
    return [
        [ clientRect.left, clientRect.left + clientRect.width ],
        [ clientRect.top, clientRect.top + clientRect.height ]
    ];
}


function intersect(elemA, elemB) {
    var posA = getPositions(elemA),
        posB = getPositions(elemB),
        isOverlap = false;

    if (posA[0][0] < posB[0][1] && posA[0][1] > posB[0][0] &&
        posA[1][0] < posB[1][1] && posA[1][1] > posB[1][0])
        isOverlap = true;

    return isOverlap;
}
isxaker
  • 8,446
  • 12
  • 60
  • 87
3

You can do it using Element.getClientRects() method which returns a collection of rectangles that indicate the bounding rectangles for each box in a client.

The returned value is a collection of ClientRect objects, one for each CSS border box associated with the element. Each ClientRect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. For tables with captions, the caption is included even though it's outside the border box of the table.

Alexander Dayan
  • 2,846
  • 1
  • 17
  • 30