Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery draggable revert is not pixel perfect

I'm experimenting with jQuery draggable. When dragging then reverting, the revert does not always position the draggable object exactly back to where it started - it can be several pixels out.

html:

<div id="draggable2" class="formsection ui-widget-content resizable">
<p>I am draggable2</p>
</div>

jquery:

$(".formsection").draggable({
    grid: [20, 20],
    revert: true, 
    zIndex: 9700,
}); 

css

.formsection{position:absolute; top:20px; left:20px; width: 220px; height: 80px; padding: 5px; float: left; margin: 0 10px 10px 0; font-size: .9em; 
             background-color:#eee; border:solid 1px green; }

It seems to work first time, but if a drag a second time it is always out, but inconsistently so. Anyone know how to fix?

like image 529
Journeyman Avatar asked Apr 09 '11 08:04

Journeyman


2 Answers

This is a known bug in jQuery UI with "revert" and "grid". There is a ugly workaround in the bug comments, but it involves changing jQuery UI itself.

I've created a much simpler workaround:

$(".formsection").draggable({
    grid: [20, 20],
    zIndex: 9700,
    stop: function(event, ui) {
        this._originalPosition = this._originalPosition || ui.originalPosition;
        ui.helper.animate( this._originalPosition );
    }
});

The first time the Draggable is dragged, it saves the orginalPosition, because that's the only time it's correct, and then use the animate method with our saved position the consecutive times, instead of using the built in "revert".

Example on jsfiddle

like image 61
Sindre Sorhus Avatar answered Nov 14 '22 20:11

Sindre Sorhus


I solved it like this:

$( ".formsection" ).bind( "dragstart", function(event, ui) {
    ui.originalPosition.top = $(this).position().top;
    ui.originalPosition.left = $(this).position().left;
});

The advantages of this method is that you can still use the built in revert functionality of draggable (and droppable)

like image 40
sambooka Avatar answered Nov 14 '22 20:11

sambooka