Skip to content

Instantly share code, notes, and snippets.

@PsyGik
Created May 14, 2021 16:06
Show Gist options
  • Save PsyGik/d6ada3960d0c7b4645e3a7c3e4bf1704 to your computer and use it in GitHub Desktop.
Save PsyGik/d6ada3960d0c7b4645e3a7c3e4bf1704 to your computer and use it in GitHub Desktop.
Snippet to detect collision and intersection between two DOM elements
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