Question

I have two squares (divs) side by side. When you drag an item around inside of one I want it restricted to that one, but, if you move your mouse cursor out of it and into the next square over, I want the element to pop out of the first square and into the second and be restricted to the second (and then vice-versa if you move mouse back into the first again while still dragging). But, at no time should the element overlap the squares (it should be wholly always inside of either one or the other). How can I do this? I'm using jQuery UI.

http://jsbin.com/gecucotu/1/edit?js,output

Was it helpful?

Solution

Couldn't get jQuery UI to do it, but, was able to do it using Vanilla JavaScript

http://jsfiddle.net/cmcculloh/676fr/

var dragging = false;
var lastE;

$('#t1').mousedown(function(e){
    dragging = true;
});

$('body').mousemove(function(e){
    lastE = e;  
}).mouseup(function(e){
    dragging = false;
});


var placeT = function placeT(e) {
    var newX = Math.round((e.pageX - 2)/20) * 20;
    var newY = Math.round((e.pageY - 2)/20) * 20;

    if(newX <= 100){
         $('#t1').offset({ left: newX });
    }else if(newX >= 220 && newX <= 300){
         $('#t1').offset({ left: newX });
    }else{

    }
     $('#t1').offset({ top: newY });
}

var drag = function drag() {
    if(dragging){
        placeT(lastE);
    }
    window.setTimeout(drag, 1);    

};
window.setTimeout(drag, 100);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top