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.
All you need to do is define draggable=true in your element and code the relevant ondragstart and ondragend logic. This works with both vanilla JS and frameworks like React.
The . position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with . offset() , which retrieves the current position relative to the document.
Use the "containment" option:
jQuery UI API - Draggable Widget - containment
The documentation says it only accepts the values: 'parent'
, 'document'
, 'window'
, [x1, y1, x2, y2]
but I seem to remember it will accept a selector such as '#container' too.
$(function() { $( "#draggable" ).draggable({ containment: "window" }); });
of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html
In order to limit the element inside its parent:
$( "#draggable" ).draggable({ containment: "window" });
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
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