Skip to content

Instantly share code, notes, and snippets.

@JayWood
Created September 8, 2015 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JayWood/538fb642fc4a99764301 to your computer and use it in GitHub Desktop.
Save JayWood/538fb642fc4a99764301 to your computer and use it in GitHub Desktop.
Detect if two elements are colliding/overlapping
/**
* Detects if two elements are colliding
*
* Credit goes to BC on Stack Overflow, cleaned up a little bit
*
* @link http://stackoverflow.com/questions/5419134/how-to-detect-if-two-divs-touch-with-jquery
* @param $div1
* @param $div2
* @returns {boolean}
*/
var is_colliding = function( $div1, $div2 ) {
var x1 = $div1.offset().left,
y1 = $div1.offset().top,
h1 = $div1.outerHeight(true ),
w1 = $div1.outerWidth(true ),
b1 = y1 + h1,
r1 = x1 + w1,
x2 = $div2.offset().left,
y2 = $div2.offset().top,
h2 = $div2.outerHeight(true ),
w2 = $div2.outerWidth(true ),
b2 = y2 + h2,
r2 = x2 + w2;
if( b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2 ) {
return false;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment