Jonny Campbell
Jonny Campbell

Reputation: 11

How do I link two sortable lists in JavaScript?

I am using RubuXa's Sortable to create a sortable list. I am trying to link this list to another list so that when I update the sortable list (change order / delete item) the other list updates to reflect the changes.

i.e. when a user drags 'Item Heading 1' to position #2 in the Sortable List the Display List is updated to show the new positions.

The HTML

    <ul id="sortable-list">
      <li>Item Heading 1</li>
      <li>Item Heading 2</li>
      <li>Item Heading 3</li>
    </ul>

    <ul id="display-list">
      <li>
        <h3>Item Heading 1</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
      </li>
      <li>
        <h3>Item Heading 2</h3>
        <p>Sed ullamcorper varius finibus. Cras semper libero a nibh laoreet.</p>
      </li>
      <li>
        <h3>Item Heading 3</h3>
        <p>Nunc tincidunt pharetra augue, non tincidunt nunc cursus vitae.</p>
      </li>
    </ul>

The JavaScript

    $(function () {
      var el = document.getElementById('sortable-list');
        var sortable = Sortable.create(el, {
        group: "name",
        store: {
            get: function (sortable) {
                var order = localStorage.getItem(sortable.options.group.name);
                return order ? order.split('|') : [];
            },
            set: function (sortable) {
                var order = sortable.toArray();
                localStorage.setItem(sortable.options.group.name, order.join('|'));
            }
        },
        delay: 0,
        animation: 150
        });
    });

JSFiddle

Upvotes: 1

Views: 153

Answers (0)

Related Questions