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
source to share
No one has answered this question yet
Check out similar questions: