tags:

views:

2077

answers:

3

i want to detect to see if an element was dragged out of container.

for example:

<div id="container">
    <img src="xxx.png" />
</div>

if i am drag that img element out of the div. i will remove the img element, but i do not know how to detect when the img is out of div.

i am use jquery drag and drop library.

A: 

you need to add a div outside of your container

<div id="droppableDiv">
    <div id="container">
        <img src="xxx.png" />
    </div>
</div>

and then make it droppable by adding a function similar to:

 $("#droppableDiv").droppable ({  
   drop: function() { alert('dropped'); }  
});

instead of the alert('dropped'); part you could add a little bit of code that removes the img element from the container div.

here is a example that does some other thing but makes use of droppable and draggable objects, maybe it can help you understand how it works!

hope this helps

-Fortes

Fortes
A: 

thank your provides a solution.

I have found an other solution without need an outer div for this problem.

I am use "distance" option to detect how long mouse has moved, then use "stop" option to remove element.

$(".droppable").droppable({
    drop: function(event, ui) {
        var obj = $(ui.draggable).clone();
        obj.draggable({
                    distance: 100,//used to measure how far my mouse moved.
                    helper: 'clone',
                    opacity : 0.35,
                        stop: function(event, ui) {
                            $(this).remove();//remove this element.
                        }

                      }

       );//obj.draggable
    }//drop
})
anru
A: 

There is an easy way to do this.

  1. Set child to draggable
  2. Set parent to droppable
  3. Set a flag which if true on drag stop removes the element
  4. Unset this flag in the parents on drop function
  5. child dragged out of parent == child not dropped into parent

So when you move the child around in the parent nothing happens (removeMe flag is unset) and it moves back to original position.

If you drag the child outside of the parent the removeMe flag isn't unset and the drag stop method removes the child.

javascript

$("#draggable").draggable({
  start: function(event, ui) {
    // flag to indicate that we want to remove element on drag stop
    ui.helper.removeMe = true;
  },
  stop: function(event, ui) {
    // remove draggable if flag is still true
    // which means it wasn't unset on drop into parent
    // so dragging stopped outside of parent
    if (ui.helper.removeMe) {
      ui.helper.remove();
    }
  },
  // move back if dropped into a droppable
  revert: 'valid'
});

$("#droppable").droppable({
  drop: function(event, ui) {
    // unset removeMe flag as child is still inside parent
    ui.helper.removeMe = false;
  }
});

html

<div id="droppable">
  <p id="draggable">Drag me!</p>
</div>
jitter