JSFiddle - React, Tailwind, and code Playground

by Quentin Sanglier

HTML

<div id="labelzone">

</div>

CSS

#labelzone{
    float:left;
    width:500px;
    height:500px;
    border: 1px solid black;
    position: relative;
}

.label{
    position:absolute;
    border:1px solid black;
    background-color:white;
}

JavaScript

var borderWidth = 2;

function isInside (pt, div)
{
    var x = parseInt($(div).css("left"));
    var y = parseInt($(div).css("top"));
    var w = $(div).width () + borderWidth;
    var h = $(div).height ();
    
    if (pt[0] >= x && pt[0] <= x + w &&
        pt[1] >= y && pt[1] <= y + h)
        return true;
    return false;
}

function collision (div1, div2)
{
 
    var x = parseInt($(div1).css("left"));
    
    var y = parseInt($(div1).css("top"));
    var w = $(div1).width () + borderWidth;
    var h = $(div1).height ();
    var pos = [x, y];
    
    
    if (isInside (pos, div2))
        return true;
    pos = [x + w, y];
    if (isInside (pos, div2))
        return true;
    pos = [x + w, y + h];
    if (isInside (pos, div2))
        return true;
    pos = [x, y + h];
    if (isInside (pos, div2))
        return true;

    return false;
}

function addLabel (newLeft, newTop)
{
       
    var newLab = document.createElement ("div");
    newLab.className = "label";
    $(newLab).css({"left": newLeft+"%", "top": newTop + "%"});
    var labels = $("#labelzone > div");
    newLab.innerHTML =  "00" + (labels.length + 1); // manage 0s
    $("#labelzone").append (newLab);
  
    var isCollision = false;
    var cpt = 1;
    do
    {
        isCollision = false;
        $(labels).each (function () {
            if (! isCollision && collision (this, newLab))
               isCollision = true;
         });

        if (isCollision)
             $(newLab).css({"left": (newLeft + cpt++) + "%", "top": (newTop + cpt++) + "%"});
        
    } while (isCollision);
}



$(document).ready (function () {
       addLabel (0, 8);
    addLabel (0, 11);
    addLabel (1, 10);
    addLabel (2, 7);
    
    });