You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

Drag Dropping a Helper (or something else) with jQuery UI

I was having issues using jquery UI’s draggable and dropping something other than what I was dragging into a sortable. So this example, but dropping something else.

Originally I was trying to do it with Helpers. Helpers are nice, but limited in functionality and you cannot get the draggable helper element from the sortable. The right way seems to be to append / create the element within the dom once it’s been dropped. So create an element template and drop it in on the sortable’s update event.

Here is a jsfiddle with my solution.

Highlight:

var textItem = 'Text that is droppped';
var imgItem = 'Image that is dropped';

$(document).ready(function(){
	$('#sortable').sortable({
		revert: true,
		update: function(event, ui){
			if($(ui.item).hasClass('mysortable')){
			    // we don't add one if we're sorting a pre-existing item	
			} else {
				$(ui.item).removeClass('ui-state-highlight');
				$(ui.item).addClass('mysortable');
				
				if($(ui.item).hasClass('textDrag')){
					$(ui.item).html(textItem);					
				}
				if($(ui.item).hasClass('imgDrag')){
					$(ui.item).html(imgItem);					
				}
			}
		}
	});
	$('.draggable').draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
	});
	
});

Leave a comment