JSFiddle - React, Tailwind, and code Playground

by levchenko_d

HTML

<div class="field"></div>

CSS

.field{
  position: absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background: #f2f2f2;
}

.block{
  position: absolute;
  width: 100px;
  height: 50px;
  background: #00b0ef;
  box-shadow: 0 1px 3px rgba(0,0,0,.5);
  transition: 0.5s ease-out;
}

JavaScript

var blocksStorage = [];
var $f = $('.field');



function isOverlap(dimentionsA, dimentionsB){
	var A = dimentionsA,
  		B = dimentionsB,
      
      ax1 = A.left,
      ax2 = ax1 + A.width,
      ay1 = A.top,
      ay2 = ay1 + A.height,
      
			bx1 = B.left,
      bx2 = bx1 + B.width,
      by1 = B.top,
      by2 = by1 + B.height,
      
     
      isOverlapping = !(ax2 < bx1 || 
                        ax1 > bx2 || 
                        ay2 < by1 || 
                        ay1 > by2);
      
  return isOverlapping;
}

function findOverlap(dimentions){
console.log('findOverlap:',blocksStorage);
	var i=0,
  		size=blocksStorage.length;


	function _handleItem(){
  	var item = blocksStorage[i];
    console.log('_handleItem:', item);
    if(!item){
    	console.log('no overlap');
    	return;
    } else if(i < size && !isOverlap(item, dimentions)){
    	i++;
      _handleItem();
    } else {
    	alert('overlap!');
    }
  }
  
  if(size != i){
  	_handleItem();
  }
}


function generateDimentions(e){
	var x = e.clientX,
  		y = e.clientY,
      width = Math.max(Math.floor(Math.random() * 200), 100),
      height = Math.max(Math.floor(Math.random() * 100), 50),
      left = x - width/2,
      top = y - height/2;

	return {
          top: top,
          left: left,
          width: width,
          height: height
         };     
}

function createBlock(e){
	var $b = $('<div class="block"></div>'),
      dimentions = generateDimentions(e);

 	$f.append($b);
  
  findOverlap(dimentions);
  
  $b.css(dimentions);
  blocksStorage.push(dimentions);
}

$f.on('click', function(e){
	createBlock(e);
});