title: JavaScript to calculate random position for divs with no collision
body: <p>I'm trying to draw a bunch of divs inside of a container in such a way that they are randomly positioned every time the page is loaded and that there is no overlapping. I seem to be stuck in an infinite loop and without the sources loading in Chrome before crashing the page, I can't debug properly.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>    $(document).ready(function() {
        var filledAreas = new Array();
  
        var minX = 50;
        var maxX = $("#banner").width() - 150;
        var minY = 50;
        var maxY = $("#banner").height() - 150;
  
        var loops = 0;
        var loopsMax = 100;
  
        for(var i = 0; i &lt; 15; i++) {
          var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
          $newDiv = $("&lt;div class='bubble-outer'&gt;&lt;/div&gt;").css({
            'width':'100px',
            'height':'100px',
            'background-color':color,
          });
          var randX = 0;
          var randY = 0;
          var area;
          do {
            randX = Math.floor(Math.random() * (maxX - minX + 1)) + minX;
            randY = Math.floor(Math.random() * (maxY - minY + 1)) + minY;
            var area = {
              'left': randX,
              'top': randY,
              'right': randX + 100,
              'bottom': randY + 100,
            };
          } while (loops &lt; loopsMax &amp;&amp; checkOverlap(area))
  
          filledAreas.push(area)
  
          $newDiv.css({
            'position':'absolute',
            'left':randX+'px',
            'top':randY+'px',
            'display':'none'
          }).delay(1000).appendTo("#banner").fadeIn(300);
        }
  
        console.log("Loops: " + loops);
  
        function checkOverlap(area) {
          for (var i = 0; i &lt; filledAreas.length; i++) {
            var check = filledAreas[i];
            if (area.right &lt; check.left &amp;&amp; area.bottom &lt; check.top &amp;&amp; 
              check.right &lt; area.left &amp;&amp; check.bottom &lt; area.top) {
              loops++;
              continue;
            } else {
              return true;
            }
            return false;
          }
        }
      });
  </code></pre>