6

in jQuery or Javascript, how would I detect if an img tag for example is overlapping another img tag?

1

5 Answers 5

8

You can do that by finding the offset of the elements, then finding the width & height of each. It's then just a matter of simple math to determine if they're overlapping.

I'm not going to do all the work for you, but this should get you on the right track:

<div id="one"></div>
<div id="two"></div>

<script>
var offsetOne = $('#one').offset();
var offsetTwo = $('#two').offset();
var widthOne = $('#one').width();
var widthTwo = $('#two').width();
var heightOne = $('#one').height();
var heightTwo = $('#two').height();
</script>

All that's left is to use the two offset's .top & .left along with the widths and heights to determine if there's an overlap. Check out the links to documentation in each of the functions in the first paragraph of my answer.

Sign up to request clarification or add additional context in comments.

4 Comments

Have any code examples or articles. I've never done anything with this type of complexity.
Oh okay I didn't realize you where talking about the actual offset(), width(), and height() methods. thanks man
var one = document.getElementById('one'); one.offsetHeight; one.offsetLeft; etc. no need for JQuery
@SephReed that is not correct. JQuery offset() gives you the position relative to the document, not offset parent.
7

I just wrote a js file for you to use =) hope it helps you... it took me a while until I finished it

You can download it from this link: solid-dotheyoverlap.js

simply include that js file and call the doTheyOverlap function with the two divs you want to know whether they're overlapping or not, and that's it!

here's a basic and simple example I made for you:

<html>
<head>
<title>Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="solid-dotheyoverlap.js"></script>
<script type="text/javascript">
    $(function() {  
        alert(doTheyOverlap($('#div0'),$('#div1')));    
    });
</script>
</head>
<body>
    <div id="div0" style="position: absolute; width : 200px; height : 200px; background-color : red">div 0</div>
    <div id="div1" style="position: absolute; width : 200px; height : 200px; background-color : yellow; top:100px; left:100px">div 1</div>
</body>
</html>

and the code for the solid-doTheyOverlap.js that I wrote is clearer and more efficient than the solution proposed by @artwl. it goes like this:

function doTheyOverlap(div0, div1){return (yInstersection(div0, div1) && xInstersection(div0, div1));}

function findSmallestY(div0, div1){
    return (div0.offset().top < div1.offset().top)? div0 : div1;
}
function yInstersection(div0, div1){
    var divY0 = findSmallestY(div0, div1);
    var divY1 = (div0 != divY0)? div0 : div1;

    return (divY0.offset().top + divY0.height()) - divY1.offset().top > 0;
}

function findSmallestX(div0, div1){
    return (div0.offset().left < div1.offset().left)? div0 : div1;
}

function xInstersection(div0, div1){
    var divX0 = findSmallestX(div0, div1);
    var divX1 = (div0 != divX0)? div0 : div1;

    return (divX0.offset().left + divX0.width()) - divX1.offset().left > 0;
}

Put it in simple words I realized that "figuring out whether 2 squares are overlapped is as simple as figuring out whether their segments (occording to the x axis and y axis) are overllaping", in javascript it would be like this "doTheyOverlap(div0, div1){return (yInstersection(div0, div1) && xInstersection(div0, div1));}", from there on it's as simple as a pair of substractions ((divY0.offset().top + divY0.height()) - divY1.offset().top > 0, (divX0.offset().left + divX0.width()) - divX1.offset().left > 0) to find out whether those segments are overlapped.

Comments

7

Another vanilla way using getBoundingClientRect(). I'm sharing this because I didn't like the answers here and this was my solution.

function checkForOverlap(el1, el2) {

    var bounds1 = el1.getBoundingClientRect();
    var bounds2 = el2.getBoundingClientRect();

    var firstIstLeftmost = (bounds1.left <= bounds2.left);
    var leftest = firstIstLeftmost ? bounds1 : bounds2;
    var rightest = firstIstLeftmost ? bounds2 : bounds1;

    //change to >= if border overlap should count
    if(leftest.right > rightest.left) {
            //
        var firstIsTopmost = (bounds1.top <= bounds2.top);
        var topest = firstIsTopmost ? bounds1 : bounds2;
        var bottomest = firstIsTopmost ? bounds2 : bounds1;

        //change to >= if border overlap should count
        return topest.bottom > bottomest.top;
    }
    else return false;

}

Comments

4

Demo

<style type="text/css">
    div{
        width:200px;
        height:200px;
        background:#EEE;
    }
    #two{
        position:absolute;
        left:100px;
        top:50px;
        background:#F60;
    }
</style>
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<script>
    console.log(isOverlap("one","two"));//true
    console.log(isOverlap("one","three"));//false
    console.log(isOverlap("two","three"));//true
    function isOverlap(idOne,idTwo){
        var objOne=$("#"+idOne),
            objTwo=$("#"+idTwo),
            offsetOne = objOne.offset(),
            offsetTwo = objTwo.offset(),
            topOne=offsetOne.top,
            topTwo=offsetTwo.top,
            leftOne=offsetOne.left,
            leftTwo=offsetTwo.left,
            widthOne = objOne.width(),
            widthTwo = objTwo.width(),
            heightOne = objOne.height(),
            heightTwo = objTwo.height();
        var leftTop = leftTwo > leftOne && leftTwo < leftOne+widthOne 
                && topTwo > topOne && topTwo < topOne+heightOne,
            rightTop = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne 
                && topTwo > topOne && topTwo < topOne+heightOne,
            leftBottom = leftTwo > leftOne && leftTwo < leftOne+widthOne 
                && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne,
            rightBottom = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne 
                && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne;
        return leftTop || rightTop || leftBottom || rightBottom;
    }
</script>

2 Comments

Next time, put it on jsfiddle.net from the start so people can check and cherish your work. :)
@Phrogz thanks,i have put it on jsfiddle,and edited my answer
3

@solid snake, i rewrote your code into a more concise form:

function doTheyOverlap(el0, el1)
{
    var elY0 = (el0.offsetTop < el1.offsetTop)? el0 : el1;
    var elY1 = (el0 != elY0)? el0 : el1;
    var yInstersection = (elY0.offsetTop + elY0.clientHeight) - elY1.offsetTop > 0;

    var elX0 = (el0.offsetLeft < el1.offsetLeft)? el0 : el1;
    var elX1 = (el0 != elX0)? el0 : el1;
    var xInstersection = (elX0.offsetLeft + elX0.clientWidth) - elX1.offsetLeft > 0;

    return (yInstersection && xInstersection);
}

As this answer is still relevant despite being from 2012

Edit: updated code

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.