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".

2
  • "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 Commented Feb 6, 2015 at 8:50
  • stackoverflow.com/questions/5419134/… Commented Feb 6, 2015 at 8:52

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

getBoundingClientRect returns the rectangle of whole element, not a text inside it.
I agree with your offer to use Element.getClientRects()
Thank you ;) What about to vote my answer if you agree with it?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.