To properly constrain the movement of an element using jQuery UI's draggable function, you can utilize the 'containment' property. Below is an example explaining how to achieve this:
$(function() {
$("#draggable").draggable({
containment: [-100,-100,0,0]
});
});
Pay attention to the 'containment' parameter values in the code snippet above. These values represent the offset or position (depending on context) of the area from its relative position where the '.draggable' element will be restricted to during dragging.
For instance, given the following HTML structure:
<div class="bigDiv">
<div class="smallDiv" id="draggable">
</div>
</div>
and corresponding CSS styles:
body {
margin: 0;
padding: 0;
}
.bigDiv{
border: solid 1px black;
position: absolute;
top: 0;
left: 0;
height: 200px;
width: 200px;
}
.smallDiv{
opacity: 0.5;
background-color: limegreen;
position: absolute;
width: 300px;
height: 300px;
}
Based on the offset values of '.bigDiv' from its relative position (top: 0, left: 0), your 'containment' parameter should be set as [1st_param, 2nd_param, 3rd_param, 4th_param], with calculations involving container dimensions and offsets.
- 1st_param - Leftmost offset from relative position (-100)
- 2nd_param - Topmost offset from relative position (-100)
- 3rd_param - Lowest left offset (calculated accordingly)
- 4th_param - Lowest top offset (calculated accordingly)
For a visual demonstration, check out the Fiddle Demo. If further clarification is needed, refer to the complete code in action here, adjusting the position, width, and height values of '.bigDiv' and '.smallDiv' for different outcomes.