Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to revert position of a jquery UI draggable based on condition

I have an element which is draggable and an element which is droppable. Once the dragged item is dropped on the dropzone I am trying to execute the following jquery psuedo code:

if(draggedelement == value){  $(draggedelement).hide();  } else{  $(draggedelement).revert();  } 

where the revert() function moves the dragged item back to its original postion.

How would one accomplish this?

P.S. I am aware of the draggable 'revert' option, however this only activates if the dragged item does not make it to the dropzone.

like image 790
Mazatec Avatar asked Jun 21 '10 20:06

Mazatec


People also ask

What is revert in jQuery?

Revert a jQuery draggable object back to its original container on out event of droppable.

What is the syntax of the draggable function?

The draggable (option) method specifies that an HTML element can be moved in the HTML page. Here, the option parameter specifies the behavior of the elements involved. Syntax: $(selector, context).

How do you drag and drop in jQuery?

Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port. If the value of this option is set to false, it will prevent the DOM elements to be dragged .


1 Answers

There are some built-in options for this, on your .draggable(), set the revert option to 'invalid', and it'll go back if it wasn't successfully dropped onto a droppable, like this:

$("#draggable").draggable({ revert: 'invalid' }); 

Then in your .droppable() set what's valid for a drop using the accept option, for example:

$("#droppable").droppable({ accept: '#draggable' });​ 

Anything not matching this selector gets reset when you let go, you can see a full demo here. The accept option also takes a function if you need filtering a selector can't provide, like this:

$("#droppable").droppable({    accept: function(dropElem) {     //dropElem was the dropped element, return true or false to accept/refuse it   } });​ 
like image 115
Nick Craver Avatar answered Sep 19 '22 18:09

Nick Craver