views:

100

answers:

1

Hi,

I use draggable/droppable JQuery feature as follows

div.container {
    height:400px;
}

<div class="container" id="source">
    <div id="0">Item 0</div>
    <div id="1">Item 1</div>
    <div id="2">Item 2</div>
</div>

<div class="container" id="target"></div>

$("#source div").draggable({
    helper:"clone",
        revert:"invalid"
    });

I would like to know whether is possible inject an object inside a context of a draggable object. Something like

var contextualObject = {"property":"value"};

$("#source div").draggable({
    helper:"clone",
        revert:"invalid",
        injected:contextualObject
    });

So in target container i could use something like (Notice second alert statement)

$("#target").droppable({
    accept:"#source div",
tolerance: "fit",
drop:function(e, ui) {
        alert("You have dropped id " + $(this).attr("id"));

        alert("Its contextual value is: " + $(this).draggable("option", "injected.property"));
}});

How can i do it ?

regards,

+1  A: 

jQuery data is made for this sort of thing.

$("#source div").draggable({
    helper:"clone",
        revert:"invalid",
        start: function(evt,ui) {
           $(this).data('injected', contextualObject)
        }
    });

Then, in your droppable:

 var obj = $(ui.draggable).data('injected');
 console.log(obj.property);

A couple of notes:

  • You should use ui.draggable in your drop to get the item that is drag and dropped. this is the item getting dropped on
  • Element id's should start with a letter, not a number.

I have a working demo here.

seth
Have you try it ? It does not appear to work. In droppable it complains obj is undefined.
Arthur Ronald F D Garcia
I didn't try it but I have now and fixed the bug in it. You should use `ui.draggable` for the element that is being dragged. this is the droppable element. Sorry about that.
seth
Now it works. Thank you a lot!
Arthur Ronald F D Garcia
You are welcome. Sorry about the initial hiccup.
seth