1

The JQuery UI draggable widget has a revert options which determines under what circumstances the dragged element should revert back to its initial location.

The documentation specifies that the string "invalid" may be provided in which case the dragged element reverts to its original location if not dropped on a droppable widget. Another option is to provide revert with a function which will determine whether the widget should revert when the dragging stops.

In my situation, I'd like both of these behaviors; I want the widget to revert if dropped on a non-droppable element, but I also want to do some on-the-fly custom validation, failure of which should result in a revert. How can I incorporate both of these functionalities?

Isaac Kleinman
  • 3,994
  • 3
  • 31
  • 35
  • 2
    Not a dup, but I think this question will solve your problem: http://stackoverflow.com/questions/14571919/adding-a-function-to-jquery-draggable-revert-event – Anders Aug 06 '15 at 21:14

1 Answers1

1

When revert is a function, the first argument passed to it is the droppable or sortable widget it was dropped on, if one exists, or false otherwise. For example:

$(elt).draggable({
    revert: function(dropped) {
        var result = false;
        // dropped can safely be typecast to boolean
        // if you want to call jquery functions on it check for "false" first
        result = customLogic || (dropped && $(dropped).is(".valid-droppable-class") ); 
        return result;
    }
});

Using revert:"invalid" is equivalent to revert: function(dropped) { return dropped; }

blgt
  • 8,135
  • 1
  • 25
  • 28
  • Yes, I figured this out. Turns out I get stuck with the fact that my custom validation logic happens asynchronously, so I have to bark up a different tree for this one. – Isaac Kleinman Aug 07 '15 at 12:50