My implementation of the following can be found on jsfiddle.net
I have four divs. My goal is to make them draggable around the page but NOT to allow them to overlap one
This is a bit more complex than it looks.
Essentially what you need to do is get both sets of coordinates, those for the current (moving) element, and the one with which it has collided. Once a collision is detected, find out which axis has the smallest difference, then snap those coordinates.
var ac = a.getBoundingClientRect(); // coordinates for element 'a'
var bc = b.getBoundingClientRect(); // and 'b'
// assuming both boxes are same size...
// if not, use your existing collision code.
if(Math.abs(ac.top - bc.top) < ac.height && Math.abs(ac.left - bc.left) < ac.width) {
// collision here...
if(Math.abs(ac.top - bc.top) < Math.abs(ac.left - bc.left)) {
// vartical offset is smaller, so snap 'y's
if(ac.top < bc.top) { // a is above b, so snap a's bottom to b's top
a.style.top = bc.top - ac.height - 1 + 'px';
}
else {
a.style.top = bc.top + bc.height + 1 + 'px';
}
}
else { // here, horizontal offset is smaller, so snap 'x's
if(ac.left < bc.left) { // a is to the left of b, so snap a's right to b's left
a.style.left = bc.left - ac.width - 1 + 'px';
}
else {
a.style.left = bc.left + bc.width + 1 + 'px';
}
}
}
That should solve your problem...