Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ui draggable - how can I prevent dragging outside the top of my document?

I've set up a jquery draggable, which can be moved around the entire document, it's not contained by anything, and this is acceptable, as when the user drags, I want them to be able to drag as far down the page (or left or right) as they wish.

Indeed, the only restriction I want - is that they should be prevented dragging the element outside of the top of the page.

Is it possible to prevent dragging outside only one edge of a container?

like image 335
Mazatec Avatar asked Nov 26 '12 13:11

Mazatec


People also ask

How do I limit a draggable area?

There is an option we can set to the draggable method to limit the area of dragging the element within a parent element. To do this, we just have to set the element as the value of that option.

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 .

How does jQuery ui draggable work?

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.

What is the syntax of the draggable function?

Syntax: $(selector, context). draggable ("action", [params]);


2 Answers

You could overwrite the position of the element being dragged.

This fiddle is an example of the position overwriting : http://jsbin.com/ufarif/7/edit

Here is an example to not permit to be more close than 80 px of the left border

$('[id^="drag-"]').each(function() {
    $(this).draggable({
        opacity: 0.7,
        cursorAt: { top: 15, left: 50 },        
        scroll: true,
        stop: function(){},  
        drag : function(e,ui){            
            //Do not permit to be more close than 80 px of the left border
            console.log(ui.position.left);      
            if(ui.position.left < 80)    
                ui.position.left = 80;
        });
});
like image 66
sdespont Avatar answered Oct 19 '22 23:10

sdespont


You can use the containment option to prevent dragging outside the window :

$("#id").draggable({
    handle: tr_top,
    containment: "window"
});
like image 43
Chiragkumar Thakar Avatar answered Oct 20 '22 00:10

Chiragkumar Thakar