Jquery ui draggable - how can I prevent drag and drop from outside my document?

I have set up a jquery draggable that can be moved throughout the document, it is not contained in anything, and this is acceptable, because when the user drags, I want them to be able to drag so far the page (either left or right) as I like.

In fact, the only limitation I want is that they should prevent the item from being dragged out of the top of the page.

Is it possible to prevent dragging beyond just one edge of the container?

+4
source share
2 answers

You can overwrite the position of the item being moved.

This script is an example of rewriting a position: http://jsbin.com/ufarif/7/edit

Here is an example to not be closer to 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; }); }); 
+6
source

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

 $("#id").draggable({ handle: tr_top, containment: "window" }); 
0
source

All Articles