I'm working on a WordPress website and I want the user to have the ability to reorder the sidebar widgets even if the site reloads.
So I'm using Sortable JS and using the saving and restoring of the sort as I plan to store it in localStorage but I couldn't make it work. It's pretty straightforward in the documentation and the demo but for some reason, it's not working for me and I'm not sure what I'm missing.
Below is the default sorting of the elements.
And once I reorder these widgets, I get this result.
I believe the issue was the naming of the keys is incorrect. See the highlighted text with blue in the image below. It's missing in the array called from the set method.
So the highlighted with blue here is the log from the get: function (sortable) method and the array output is from the set: function (sortable) .
Here's a quick video to see it more clearly.
Below is my code.
let el = document.getElementById('sticky-sidebar');
Sortable.create(el, {
group: 'foo',
animation: 100,
draggable: ".widget_block",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
console.log(order)
return order ? order.split('|') : [];
},
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: function (sortable) {
var order = sortable.toArray();
console.log(order)
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
}
});