Reputation: 5926
Please take a look at this jsFiddle.
What I am trying to achieve is to allow user to drag one of the three items on top and drop them into the sorted list. I have added a custom helper which is a placeholder right now and will be used for showing a preview of what that item will look like.
For the sake of discussion lets say the three draggable elements are source items, and what ends up in the sortable list is target items. What I am having difficulty is passing the right content to the stop
function in the sortable list and inserting that content into the list instead of default clone of the source item. I also want to pass along some additional information with the source item. For example I want to know in the stop function if the element came from one of draggable source items or it is just one of the target items that is being reordered.
If you check the console you can see some of the unsuccessful attempts that I have made. I tried setting values in event.data
but I get TypeError: event.data is null
in the start and stop functions of the sortable list. So I think I am missing something here.
To reiterate my question, there are two related issues I am facing:
start
and stop
function of the sortable list?Any help will be appreciated.
Upvotes: 3
Views: 5127
Reputation: 14025
It is a tricky question.
The main problem is that the sortable
and draggable
widgets working together use clones of elements and not the elements themselves.
As the JQuery data
method store data for an element, it is not easy to bring the information because of the clone creation behavior described above.
A workaround could be to use a simple div
to store and retrieve the data in the events callback. It is working because there is always only one element dragged.
Here is the code and the fiddle : http://jsfiddle.net/ghMaP/4/
<ul id="draggable">
<li class="ui-state-default">Button</li>
<li class="ui-state-default">Text Field</li>
<li class="ui-state-default">Image</li>
</ul>
<ul id="sortable" class="ui-state-highlight">
</ul>
<!-- New div used to store and retrieve data of dragged element -->
<div id="tmp"></div>
$(document).ready(function() {
//Shortcut on the temp div
$tmp = $("#tmp").get(0);
$("#sortable").sortable({
start: function(event, ui) {
},
stop: function(event, ui) {
//Here, we retrieve data from the temp div
console.log("isNew : ", jQuery.data($tmp, "isNew"));
console.log("resultHTML : ", jQuery.data($tmp, "resultHTML"));
}
});
$("#draggable li").draggable({
connectToSortable: "#sortable",
start: function(event, ui) {
//Store info in a tmp div
jQuery.data($tmp, "isNew", true);
jQuery.data($tmp, "resultHTML", "<b>Here I will add some custom html to EVENT data</b>");
},
helper: function(event) {
return "<div class='custom-helper'>Custom helper for " + $(this).context.innerHTML + "</div>";
},
revert: "invalid"
});
});
Upvotes: 3