I have a Jquery UI sortable where the sortable boxes are centered in their container using margin: 0 auto
.
I use the axis: 'y'
setting in the sortable so that the boxes can only move vertically.
While sorting, the dragged box moves to the left of the container
Using draggable with axis: y
does not cause this problem, it seems to be related to sortable widget.
I replicated the bug in this jsfiddle. Any ideas?
The issue is that, jQuery UI applies position:absolute
upon dragging - Causing the element to be positioned at top:0
, left:0
of closest positioned element, or the window.
One option to fix this issue is to use a custom positioned helper for dragging using the helper
option. You can make use of the jquery UI position()
utility method for easily positioning the helper relative to the original element as follows:
$('#container').sortable({
axis: 'y',
helper: function(event, elm) {
return $(elm).clone().position({
my: "left",
at: "left",
of: elm
});
}
});
* { /*for stack snippet demo*/
margin: 0;
padding: 0;
}
#container {
width: 200px;
text-align: center;
height: 300px;
border: 1px solid green;
position: relative;
}
.draggable {
width: 100px;
height: 100px;
background: yellow;
margin: 10px auto;
cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="container">
<div class="draggable"></div>
<div class="draggable"></div>
</div>
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