jeudi 10 décembre 2020

How can I prevent box overlap in my random position script?

This code changes the horizontal size and location randomly whenever the page loads. I'd like to modify div.item so that they don't overlap. Basically, it will draw these divs when page loads with different size and position. Currently, they are being overlapped on each other. How can I prevent them?

I'll write my code down below.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <div id='container'>
      <div class='item'></div>
      <div class='item'></div>
      <div class='item'></div>
      <div class='item'></div>
      <div class='item'></div>
      <div class='item'></div>
      <div class='item'></div>
    </div>
    #container {
      position: relative;
     display: block;
      width: 500px;
      height: 500px;
      background: #ccc;
    }

    .item {
      min-width: 50px;
      max-width: 80%;
      min-height: 50px;
      max-height: 100px;
      background: #e00;
      position: absolute;
      border: 1px solid;
    }
            function randomFromTo(from, to) {
          return Math.floor(Math.random() * (to - from + 1) + from);
        }

        function moveRandom(obj) {
          /* get container position and size
           * -- access method : cPos.top and cPos.left */
          var cPos = $('#container').offset();
          var cHeight = $('#container').height();
          var cWidth = $('#container').width();

          // get box padding (assume all padding have same value)
          var pad = parseInt($('#container').css('padding-top').replace('px', ''));

          // get movable box size
          var bHeight = obj.height();
          var bWidth = obj.width();

          // set maximum position
          maxY = cPos.top + cHeight - bHeight - pad;
          maxX = cPos.left + cWidth - bWidth - pad;

          // set minimum position
          minY = cPos.top + pad;
          minX = cPos.left + pad;

          // set new position           
          newY = randomFromTo(minY, maxY);
          newX = randomFromTo(minX, maxX);

          obj.offset({
            top: newY,
            left: newX
          });
        }

        var css_test_idx = 100;

        $('.item').draggable()
          .mousedown(function() {
            $(this).css('z-index', css_test_idx);
            css_test_idx++;
          });

        $('.item').each(function() {
        var w = Math.floor(Math.random() * 15) + 35 + '%';
          $(this).css({
            'width': w,
            'z-index': parseInt(Math.random() * 10, 10) + 51
          });
          moveRandom($(this));
        });

I've searched for a few days because I'm too new to do it, but I couldn't. Please help me. https://jsfiddle.net/sweetmyo/0t8gLfys/24/




Aucun commentaire:

Enregistrer un commentaire