Skip to content Skip to sidebar Skip to footer

Javascript Check If Div Overlaps Other Div

I can't get my head around this problem, so i hope that you guys can help me fixing it. The thing is that I want to check if an div is overlapping an another div when they are dyna

Solution 1:

I guess there is a typo in your script, since newX2 >= oldX2 || newX2 <= oldX2 is always true :-)

But the condition in order to not have any overlapping is that (I reason on segments since you are dealing axis by axis here) new segment is before the old one :

      newX1----------------newX2        oldX1---------------oldX2

or the second one is after first one :

         oldX1---------------oldX2    newX1----------------newX2

So the corresponding condition is the following one :

functionoverlaps() {
    var minOldX = Math.min(oldX1, newX1),
        maxOldX = Math.max(oldX1, newX1),
        minNewX = Math.min(oldX2, newX2),
        maxNewX = Math.max(oldX2, newX2); 

    return (
        maxNewX <= minOldX || // <- first case
        minNewX >= maxOldX    // <- second case
    );
}

Post a Comment for "Javascript Check If Div Overlaps Other Div"