Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  112] [ 7]  / answers: 1 / hits: 32464  / 15 Years ago, wed, july 22, 2009, 12:00:00

When using jQuery UI draggables and droppables, how do you change the dragged-and-dropped element on drop? I am trying to drag one DIV to another sortable DIV. On drop, I'd like to change the classes on the dropped DIV and change its innerHTML content.



After reading various StackOverflow questions, my code looks like this:



$(.column).droppable({
accept: '.element-dragging',
drop: function(event, ui) {
if ($(ui.draggable).hasClass(elemtxt)) {
$(ui.draggable).replaceWith('<div class=element element-txt>This text box has been added!</div>');
}
}
})


It's not working for me. :-(



A full copy of my code is located at http://www.marteki.com/jquery/bugkilling.php.


More From » jquery

 Answers
40

Taking the full javascript code from the link you gave, you can change it as follows to make it work:



$(function() {
$(.elementbar div).draggable({
connectToSortable: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
helper: 'clone',
revert: 'invalid'
});
$(.elementbar div, .elementbar div img).disableSelection();
$(.column).sortable({
connectWith: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
placeholder: 'ui-sortable-placeholder',
tolerance: 'pointer',
stop: function(event, ui) {
if (ui.item.hasClass(elemtxt)) {
ui.item.replaceWith('<div class=element element-txt>This text box has been added!</div>');
}
}
});
$(.element).addClass(ui-widget ui-widget-content ui-helper-clearfix ui-corner-all);
});


There were a couple of issues:




  1. The drop event (that you show in your question) wasn't firing because you weren't accepting the right content.

  2. If you have both .sortable & .droppable you end up with weird double events firing. This is unnecessary anyway, since you can effectively grab the drop event from sortable's events given that you've linked it with the draggable.



One other thing to note - it would have been nicer to use the sortable's receive event instead of stop (since stop gets fired every time any sorting stops & receive is specifically there to fire when you drop a new item into the sort list), but it doesn't work properly because the item hasn't yet been added to the sortable list, so you aren't able to change it at that point. It works ok on stop simply because none of the other sortable items have the elemtxt class.


[#99082] Friday, July 17, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;