JQuery UI Drag n’ Drop Reverting

The jQuery UI is a very powerful tool that can greatly increase the interactivity of websites. Sometimes it doesn’t always provide the exact use we require. A prime example of this can be seen in the revert option for drag and drop objects. While the provided tools meet certain situations, the ability to revert an object back to its initial position when the page is loaded is not there. That’s where this friendly little demo comes in.

Below is a useful example of how to obtain the initial position of an object, set a variable to determine where the object has been dropped, and revert that object back to the original position all using the power of jQuery.

HTML

The markup for the html consisted of three elements: two <div> tags for the draggables and one <div> tag for the droppable.

<div id="drag" class="draggables ui-widget-content">
<!-- I revert back to this position always when not dropped on a droppable object. -->
</div>
<div id="drag2" class="draggables ui-widget-content">
<!-- I revert back to the last position I was dropped on -->
</div>
<div id="drop" class="ui-widget-header">
<!-- This is the drop target -->
</div>

CSS

The theme being used is UI Lightness from the jQuery UI CSS. The only CSS that needs to be written is for the positioning of the draggable and droppable objects.

.draggables {
width: 150px;
height: 150px;
float: left;
padding: 5px;
margin: 5px;
}
#drop {
width: 150px;
height: 150px;
float: left;
padding: 5px;
margin: 5px;
}

JS

The first step is to obtain the initial position of the draggable object that should always revert back when not dropped on a droppable object.

$( '#drag' ).data( 'left', $( '#drag' ).position( ).left ).data( 'top', $( '#drag' ).position( ).top);

=

Next, a variable is needed that will indicate whether or not a draggable object had been released on a droppable object. The activate and drop events are perfect for this situation. The activate event sets a hover variable to 0 (off) to insure a neutral drop zone when an item has begun to move. The drop event then sets the variable to 1 (on).

activate: function ( event, ui ) {
$( '#drop' ).data( 'hover', 0 );
},
drop: function ( event, ui ) {
$( '#drop' ).data( 'hover', 1 );
}

Lastly, the draggable objects position needs to be determined based on where dragging stops. This is through the stop event on the draggable object. Using a conditional if statement the hover variable is checked to see if it has a value of 1 (on) and if it does not then that means the object has not dropped on the droppable object and its position animates to the initial position that was retrieved when the page was loaded.

stop: function ( event, ui ) {
if ( $( '#drop' ).data( 'hover' ) != 1)
$('#drag').animate( { 'left': $( '#drag' ).data('left'), 'top': $( '#drag' ).data( 'top' )}, 'slow');}
}

Finally, remember to include the jQuery library and the jQuery UI.

alewis

Written by Alex