Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 573
dtakis Avatar asked Jul 11 '11 19:07

dtakis


People also ask

How do I limit a draggable area?

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.

How do you make something draggable in jQuery?

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 .

What is jQuery draggable?

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.


2 Answers

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);
        }                                                   
    }
like image 72
dtakis Avatar answered Nov 15 '22 06:11

dtakis


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.

like image 30
Akkuma Avatar answered Nov 15 '22 06:11

Akkuma