views:

405

answers:

1

Hi, I'm working with connected sortable lists and need the ability to add an extra list, but it just doesn't work.

I have an XHTML like this:

<div id="content">
   <div class="line">
        <span class="element">1</span>
        <span class="element">2</span>
        <span class="element">3</span>
   </div>
   <div class="line">
        <span class="element">4</span>
        <span class="element">5</span>
        <span class="element">6</span>
   </div>
</div>

where elements must be sortable, and the user hast to be able to change them from one .line to the other. But when sorting, an empty extra line must be added, in case the user wants to place an element in a new line.

I tried adding a div.line to div#content, but elements cannot be dropped there.

Any idea?

Thanks!

+2  A: 

This should do what you want. But really is non trivial and strongly tailored to handle exactly markup like the one you provided. If you don't understand this or it doesn't work for you post a comment.

Check here for a quick demonstration http://jsbin.com/uhoga (http://jsbin.com/uhoga/edit for the code)

//pseudo unique id generator
var uid = 0;

function starter() {
    var lines = $("div.line");
    var len = lines.size();
    //insert empty div.line at end with "unique" id
    lines.eq(len-1).after("<div class='line' id='line"+uid+"' />");
    //make it a sortable too
    $('#line'+uid).sortable({
        //connect with other div.lines which don't have same id
        connectWith: 'div.line:not([id=line'+uid+'])',
        start: starter,
        stop: stopper,
        //needed to stop some "flickering"
        appendTo: 'div.line[id=line'+uid+']',
        items: 'span.element'
    });
    uid++;
    //refresh this sortable so it sees the newly inserted as possible "target"
    $(this).sortable('refresh');
}

function stopper() {
    //remove all div.lines which are empty (have no span.element children)
    $("div.line:not(:has(> span.element))").remove();
}

//initial setup
$("div.line").each(function(i, ele) {
    var jEle = $(ele);
    //assuming the initially present div.line elements have no id
    jEle.attr("id", "line"+uid);
    jEle.sortable({
        connectWith: 'div.line:not([id=line'+uid+'])',
        start: starter,
        stop: stopper,
        //needed to stop some "flickering"
        appendTo: 'div.line[id=line'+uid+']',
        items: 'span.element'
    });
    uid++;
});
jitter
You are the man!THANK YOU!
alcuadrado
Those are some tremendous selectors. I applaud you sir.
Adam