-
-
Save jtsternberg/c272d7de5b967cec2d3d to your computer and use it in GitHub Desktop.
Detect if two elements are colliding/overlapping
This file contains 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
/** | |
* 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 ) { | |
// Div 1 data | |
var d1_offset = $div1.offset(); | |
var d1_height = $div1.outerHeight( true ); | |
var d1_width = $div1.outerWidth( true ); | |
var d1_distance_from_top = d1_offset.top + d1_height; | |
var d1_distance_from_left = d1_offset.left + d1_width; | |
// Div 2 data | |
var d2_offset = $div2.offset(); | |
var d2_height = $div2.outerHeight( true ); | |
var d2_width = $div2.outerWidth( true ); | |
var d2_distance_from_top = d2_offset.top + d2_height; | |
var d2_distance_from_left = d2_offset.left + d2_width; | |
var not_colliding = ( d1_distance_from_top < d2_offset.top || d1_offset.top > d2_distance_from_top || d1_distance_from_left < d2_offset.left || d1_offset.left > d2_distance_from_left ); | |
// Return whether it IS colliding | |
return ! not_colliding; | |
}; |
Thanks. More cleanup
let isColliding = function (div1, div2) {
let d1Offset = div1.offset();
let d1Height = div1.outerHeight(true);
let d1Width = div1.outerWidth(true);
let d1Top = d1Offset.top + d1Height;
let d1Left = d1Offset.left + d1Width;
let d2Offset = div2.offset();
let d2Height = div2.outerHeight(true);
let d2Width = div2.outerWidth(true);
let d2Top = d2Offset.top + d2Height;
let d2Left = d2Offset.left + d2Width;
return !(d1Top < d2Offset.top || d1Offset.top > d2Top || d1Left < d2Offset.left || d1Offset.left > d2Left);
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is great, Thank you so much