JSFiddle - React, Tailwind, and code Playground
by xerxesnoble
HTML
<div class="items" id="item1"></div>
<div class="items" id="item2"></div>
CSS
body{
background-color:#202020;
}
.items{
width:100px;
height: 100px;
position:absolute;
}
#item1{
background-color: #0288D1;
}
#item2{
background-color: #FF5722;
}
JavaScript
var item1 = document.getElementById("item1");
var item2 = document.getElementById("item2");
var node1 = { x:100, y:200 };
var node2 = { x:150, y:200 };
function setItemToNode(item, node){
item.style.transform = "translate("+node.x+"px"+","+node.y+"px)";
}
function collides(a, b){
var bound1 = a.getBoundingClientRect();
var bound2 = b.getBoundingClientRect();
var x1 = bound1.left;
var y1 = bound1.top;
var b1 = y1 + bound1.height;
var r1 = x1 + bound1.width;
var x2 = bound2.left;
var y2 = bound2.top;
var b2 = y2 + bound2.height;
var r2 = x2 + bound2.width;
if (!(b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2)) return true;
else return false;
}
function forceApart(){
var v1, v2, dx, dy;
var b1 = item1.getBoundingClientRect();
var b2 = item2.getBoundingClientRect();
//Set X
if(node1.x < node2.x){
v1 = node1.x + b1.width/2;
v2 = node2.x - b2.width/2;
dx = (v1 - v2) /2;
item1.style.left = -dx + "px";
item2.style.left = dx + "px";
}else if(node1.x > node2.x){
v1 = node1.x - b1.width/2;
v2 = node2.x + b2.width/2;
dx = (v2 - v1) /2;
item1.style.left = dx + "px";
item2.style.left = -dx + "px";
}
//Set Y
if(node1.y < node2.y){
v1 = node1.y + b1.height/2;
v2 = node2.y - b2.height/2;
dy = (v1 - v2) /2;
item1.style.top = -dy + "px";
item2.style.top = dy + "px";
}else if(node1.y > node2.y){
v1 = node1.y - b1.height/2;
v2 = node2.y + b2.height/2;
d = (v2 - v1) /2;
item1.style.top = dy + "px";
item2.style.top = -dy + "px";
}
item1.innerHTML="Top: "+item1.style.top+"<br> Left: "+item1.style.left;
item2.innerHTML="Top: "+item2.style.top+"<br> Left: "+item2.style.left;
}
setItemToNode(item1, node1);
setItemToNode(item2, node2);
if(collides(item1, item2)){
setTimeout(forceApart, 1000);
}