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)
});