JSFiddle - React, Tailwind, and code Playground
HTML
<div class='widget a'>:A</div>
<div class='widget b'>:B</div>
<div class='widget c'>:C</div>
<div class='widget d'>:D</div>
<div class='widget e'>:E</div>
<div class='widget f'>:F</div>
CSS
.widget{
height: 300px;
width: 300px;
background: pink;
border: 1px solid red;
}
.a,.c,.e {
float: right;
}
JavaScript
// These arrays are going to contain many empty elements ;)
var xAxis = [];
var yAxis = [];
// Our storage. Each element looks like: [$element, top, right, bottom, left]
// Beware of cross-references! Deleted elements cannot be GCed if they're here!
var allElements = [];
/*
* @param $elem jQuery object
* @returns Object containing the jQuery object and the floored border positions
*/
function getBorders($elem) {
$elem = $elem instanceof jQuery ? $elem.first() : $($elem);
var offset = $elem.offset(); // Properties: top, left
var width = $elem.outerWidth(); // Includes padding, border.
var leftBorder = offset.left; // Position of the left border ->|
var rightBorder = leftBorder + width; // Position of the right border |<-
var height = $elem.outerHeight(); // Includes padding, border
var topBorder = offset.top; // Position of the top border _v_
var bottomBorder = offset.top + height;// Position of the bottom border ^
// Turn all numbers in integers, so that they can be used as indexes
// for arrays
// See also: http://stackoverflow.com/a/8112802/938089
return {
$elem: $elem,
top: ~~topBorder,
right: ~~rightBorder,
bottom: ~~bottomBorder,
left: ~~leftBorder
};
}
var $collection = $('.widget').each(function() {
var $this = $(this);
var info = getBorders($this);
allElements.push(info);
// The positions are floored, so that they can be used as a quick reference
xAxis[info.left] = xAxis[info.right] = info;
yAxis[info.top] = yAxis[info.bottom] = info;
});
function doesItCollide($elem) {
// WeakMaps are useful. For compatibility, I don't use them.
var info$elem = getBorders($elem);
// info$elem properties: $elem,...