Saving a sortable list into localstorage


#1

I want to save a sortable list order into localstorage. Using the following code, I can see in the console that the order is saved in localstorage but on reloading the page, the order is always the default order, not the sorted order
I am setting each <li> with a data-id. Any help would be appreciated.

  var list = $('#my-id');
  var items = list.children;
  var itemsArr = [];
  for (var i in items) {
  itemsArr.push(items[i]);
  }
  // localStorage
 var ls = JSON.parse(localStorage.getItem('data-user-sort') || '[]');
// stack overflow code
for (var j = 0; j < ls.length; j++) {
for (i = 0; i < itemsArr.length; ++i) {
  if (ls[j] === itemsArr[i].dataset.id) {
     list.appendChild(itemsArr[i]);
  }
 }    
}
$('.sortable li').on('sortable:sort', function () {
var newIdsOrder = [];
 $(this).each(function(){
  newIdsOrder.push($(this).attr('data-id'));
 });
 //Now in newIdsOrder you have array with new order of IDs
 // store in localStorage
 localStorage.setItem('data-user-sort', JSON.stringify(newIdsOrder));
 console.log(newIdsOrder)
 });

#2

Logic looks correct, error could be context related. Would be good to see JSFiddle with the issue


#3

var itemsArr = {};


#4

Here is a codepen. After a bit of work, I have code that sorts and/or hides list links and saves them to localstorage. I am trying to save 2 separate sortable lists, one on the index page and another on the About page in my codepen. Most likely due to my novice coding skills, even though they are saved in localstorage ( I can see the order saved in the inspector), the new list order is not loaded on page refresh. It’s driving me crazy trying to figure it out! Any help or suggestions would be appreciated.