Created
May 14, 2021 16:06
-
-
Save PsyGik/d6ada3960d0c7b4645e3a7c3e4bf1704 to your computer and use it in GitHub Desktop.
Snippet to detect collision and intersection between two DOM elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const collision = { | |
collide: function (el1, el2) { | |
const rect1 = el1.getBoundingClientRect(); | |
const rect2 = el2.getBoundingClientRect(); | |
return !( | |
rect1.top > rect2.bottom || | |
rect1.right < rect2.left || | |
rect1.bottom < rect2.top || | |
rect1.left > rect2.right | |
); | |
}, | |
inside: function (el1, el2) { | |
const rect1 = el1.getBoundingClientRect(); | |
const rect2 = el2.getBoundingClientRect(); | |
return ( | |
rect2.top <= rect1.top && | |
rect1.top <= rect2.bottom && | |
rect2.top <= rect1.bottom && | |
rect1.bottom <= rect2.bottom && | |
rect2.left <= rect1.left && | |
rect1.left <= rect2.right && | |
rect2.left <= rect1.right && | |
rect1.right <= rect2.right | |
); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment