Restricting the area where divs can be moved

Viewed 90

This link reflects live preview of my code.

HTML

<h1>Detect overlapping with JavaScript</h1>



<div id="area">
  <div id="box0"></div>
  <div id="box1">1</div>
  <div id="box2">2</div>
  <div id="box3">3</div>
  <div id="box4">4</div>
</div>

<div id="result"></div>


<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Javascript

var overlaps = (function() {
  function getPositions(elem) {
    var pos, width, height;
    pos = $(elem).position();
    width = $(elem).width();
    height = $(elem).height();
    return [
      [pos.left, pos.left + width],
      [pos.top, pos.top + height]
    ];
  }

  function comparePositions(p1, p2) {
    var r1, r2;
    r1 = p1[0] < p2[0] ? p1 : p2;
    r2 = p1[0] < p2[0] ? p2 : p1;
    return r1[1] > r2[0] || r1[0] === r2[0];
  }

  return function(a, b) {
    var pos1 = getPositions(a),
      pos2 = getPositions(b);
    return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
  };
})();

function m() {
  var area = $('#area')[0],
    box = $('#box0')[0],
    html;

  html = $(area).children().not(box).map(function(i) {

    if (overlaps(box, this)) {

      $("#box" + (i + 1)).removeClass('remTouch').addClass("touch");


    }
    return '<p>Red box + Box ' + (i + 1) + ' = ' + overlaps(box, this) + '</p>';


  }).get().join('');

  $('#result').html(html);


}

$('#box0').draggable({
  drag: function() {
    $(".touch").removeClass("touch").addClass('remTouch');
    m();
  }
});

I have divs in this code one of which is draggable. It pushes the div to which it is collided. The problem is that i want to bring such a functionality in it that when it is collided from upper side it moves to lower side and similarly when from left side it will move in the right direction but will not cross the border of its container div.

0 Answers
Related