Limiting the area in which divs can be moved

This link reflects a 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 being dragged. It pushes the div that it collides with. The problem is that I want to bring functionality into it such that when it collides from the top side it moves to the bottom side and similarly when from the left side it moves in the right direction but doesn't cross the border of its div container.

+3
javascript jquery html css jquery-ui


source to share


No one has answered this question yet

Check out similar questions:

4078
How to horizontally center a <div>?
2817
How can I upload files asynchronously?
2414
How can I find out which radio button is selected using jQuery?
2245
How do I refresh the page using jQuery?
1929
How to make div 100% of browser window height
1889
How do I make a div no larger than its content?
1630
Make a div to fill the height of the remaining screen.
1599
How do I move an element to another element?
1452
Creating a div element in jQuery
1375
Where should I put <script> tags in my HTML markup?



All Articles
Loading...
X
Show
Funny
Dev
Pics