jquery UI sortable: how can I change the appearance of the "placeholder" object?

JqueryJquery UiJquery Ui-Sortable

Jquery Problem Overview


In the example given at http://jqueryui.com/demos/sortable/#placeholder the placeholder is the orange box that appears when you drag any of the items.

This element can be tweaked using the placeholder option -- but it only lets you modify the class of the element as described here: http://jqueryui.com/demos/sortable/#options

I would like to customize this element more, e.g. by supplying a function to the placeholder option in the same manner that one can supply a function to the helper option.

What would I need to change (e.g. in sortable.js) to do this?

Jquery Solutions


Solution 1 - Jquery

Looking at the source for ui.sortable.js (1.7.2), you can cheat and set the placeholder to an object with a element function and an update function. The element function is used to return the placeholder dom object and the update function allows you to do things like correct its size (you can check out the _createPlaceholder function inside sortable if you want to see what the default implementation does).

So for example, the following will create a list item with the word test inside as your placeholder (note that it returns the actual dom object ([0]) and not the jQuery object itself):

$("#sortable").sortable({
	placeholder: {
		element: function(currentItem) {
			return $("<li><em>test</em></li>")[0];
		},
		update: function(container, p) {
			return;
		}
	}
});

If I'm reading source correctly, the element function should be passed the current item (jQuery object) and this should point to the sortable itself (i.e. $("#sortable") in this instance). In update you're passed the "container" which is the object which holds all the options, & the element, etc & the placeholder itself.

Please note that this is an undocumented hack, so it would obviously be unsupported & may change with the next version of jQuery UI... but it still may be of use to you, given you were talking about editing ui.sortable.js directly anyway.

Hope that helps.

Solution 2 - Jquery

A more hackish approach that I found: one can use the start option to modify the placeholder element, e.g. as follows

$("#sortable").sortable({
    start: function (e, ui) { 
      // modify ui.placeholder however you like
      ui.placeholder.html("I'm modifying the placeholder element!");
    }
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrahnView Question on Stackoverflow
Solution 1 - JqueryAlconjaView Answer on Stackoverflow
Solution 2 - JquerybrahnView Answer on Stackoverflow