Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a new item to a jquery sortable not being picked up by refresh

Tags:

jquery

I'm sorting a list of objects, some of which are regular objects, and some of which are containers of other objects.

Sortable with a handle is working fine, except when I add a new object to the container, it is not recognized after refresh.

I have the following HTML:

<button>add another option</button>
<div class="con">
    <div class="ui-state-highlight"><span class="handle">handle</span> Item 1</div>
    <div class="ui-state-highlight"><span class="handle">handle</span> Item 2</div>
    <div class="ui-state-highlight"><span class="handle">handle</span> Item 3</div>
    <div class="subthing">
        <span class="handle">handle</span>
        <div>    <span class="handle">subhandle</span> subitem</div>
        <div>    <span class="handle">subhandle</span> subitem</div>
    </div>
</div>

and script:

$('button').click(function() {
    var x = $('<div class="ui-state-highlight"><span class="handle">handle</span> newthing</div>');
    x.appendTo('.con')
    $(".con").sortable('refresh')
});

var container = $(".con");
container.sortable({
    handle: container.children().children(".handle")
});​

The Fiddle

As seen in the above code if you add a new item, it can't be sorted with the rest of the elements. I know if I say the handle property is .handle, that it will do that, but I don't want the sub-handles to be part of the sortable.

like image 443
bdwain Avatar asked Dec 27 '22 16:12

bdwain


1 Answers

What you need is:

container.sortable({
  handle: '> .handle'
});​

Check this out: http://jsfiddle.net/hQsjD/

It is the > sign that only captures the immediate .handle child.

It is important the handle argument be a string selector and not actual elements because those will not get refreshed when you call refresh.

like image 156
Yoni Baciu Avatar answered May 22 '23 06:05

Yoni Baciu