dtakis
dtakis

Reputation: 581

jquery ui draggable constrain ina axis x and given coordinates

i have

<style>
.container { position:relative; width:600px; height:400px; overflow:hidden; }

.div-inner { position:absolute; top:0px; left:0px; width:7200px; cursor:e-resize; }

</style>

$(".div-inner").draggable({ axis: "x" });

<div class="container">
     <div class="div-inner">Drag me!</div>
     </div>

i want to constrain the movement to the left and to the right of 7200 pixels width of the div inner.

if it was a scrollable element i would let it scroll from left:0px; to left: (7200-600)px;

How can i do it with draggable?

Thank you a lot!

Upvotes: 6

Views: 11097

Answers (2)

dtakis
dtakis

Reputation: 581

I found a solution:

 $(".div-inner").draggable({ axis: "x",

    stop: function(event, ui) {
        if(ui.position.left>0)
        {   
        //alert('Return back');
        $(".div-inner").animate({"left": "0px"}, 600);
        }
        else if(ui.position.left<-6800)
        {
            $(".div-inner").animate({"left": "-6400px"}, 600);
        }                                                   
    }

Upvotes: 13

Akkuma
Akkuma

Reputation: 2265

There are several examples of constrained movement available in the jQuery UI documentation: http://jqueryui.com/demos/draggable/constrain-movement.html

$(function() {
    $( "#draggable" ).draggable({ axis: "y" });
    $( "#draggable2" ).draggable({ axis: "x" });

    $( "#draggable3" ).draggable({ containment: "#containment-wrapper", scroll: false });
    $( "#draggable4" ).draggable({ containment: "#demo-frame" });
    $( "#draggable5" ).draggable({ containment: "parent" });
});

You can both contain draggables to 'parent', 'document', 'window', [x1, y1, x2, y2], an element or a selector. You can additionally allow only x or y axis movement.

Upvotes: 3

Related Questions