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!
Limit draggable area using 'containment' option It is simple. All you have to do is, add an option called containment to the draggable() method. The containment option has a value parent.
Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port. If the value of this option is set to false, it will prevent the DOM elements to be dragged .
jQueryUI provides draggable() method to make any DOM element draggable. Once the element is draggable, you can move that element by clicking on it with the mouse and dragging it anywhere within the viewport.
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With