Jquery draggable not working with containment

Dhivi picture Dhivi · Nov 7, 2013 · Viewed 7.3k times · Source

My application contains all div's with absolute css position property. Since draggable takes relative position, i need to override it with margin-left and calculate left value for dragged div. It works fine if containment is not specified,

http://jsfiddle.net/W42A4/

<div id="main"><div id="draggable">Drag me</div></div>
$( "#draggable" ).draggable({
    axis:"x",
    containment: "#main",
    stop: function( e, ui ) {
        var el = $(this);
        var newLeft = $(el).css("left");
        var newmarginLeft = $(el).css("marginLeft");
        var totalmarginShift = parseFloat(newLeft) + parseFloat(newmarginLeft);
        el
            .css("marginLeft", totalmarginShift)
            .css("left", "")
            .css("top", "")
            .css("position", "absolute");       
    }
});

I need containment to restrict draggable div movement out of box, but draggable left does not work.

Fiddle: http://jsfiddle.net/2TpPS/

I can't find what the problem is. Can anyone suggest me a solution?

Answer

tomsullivan1989 picture tomsullivan1989 · Nov 7, 2013

Just take out all of the unecessary resetting of margins you are doing. Have your jQuery simply:

$("#draggable").draggable({
    axis: "x",
    containment: "#main"
});

DEMO: http://jsfiddle.net/2TpPS/3/

If you want the box to be able to be dragged in any direction remove the axis: "x".