Skip to content Skip to sidebar Skip to footer

How To Trigger An Event When Elements (divs, Images) Touch Each Other?

I would like to know if it is at all possible to trigger a jquery event (showing contents of a ) when an element (an image) touches, enters, passes over etc. another element (a div

Solution 1:

I have to make some assumptions here. You have object A, which is moving with wasd keys, and you have objects B and C. You already have an event which listens for wasd key press and moves object A. After you move object A, you need to calculate the bounds of A (left, right, top, bottom) and compare with the bounds of object B and object C.

You can use $element.offset() to get the left and top, then right is left + width and bottom is top + height.

So once you have that for all objects, object intersect:

aTopOverlap = a.top > b.top && a.top < b.bottom;
aBottomOverlap = a.bottom > b.top && a.bottom < b.bottom;
aLeftOverlap = a.left > b.left && a.left < b.right;
aRightOverlap = a.right > b.left && a.right < b.left;
aVerticalOverlay = b.top > a.top && b.bottom < a.bottom;
aHorizontalOverlay = b.left > a.left && b.right < a.right;

if ((aTopOverlap || aBottomOverlap || aVerticalOverlay) && (aLeftOverlap || aRightOverlap || aHorizontalOverlay)) {
    //collision logic here
}

Post a Comment for "How To Trigger An Event When Elements (divs, Images) Touch Each Other?"