How can i inject an object inside a context of a draggable element in JQuery?
-
07-07-2019 - |
Question
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,
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow