move items in list javascript code example
Example 1: move list items up and down using javascript
window.onload = function () {
var upLink = document.querySelectorAll(".up");
for (var i = 0; i < upLink.length; i++) {
upLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.previousElementSibling)
wrapper.parentNode.insertBefore(wrapper, wrapper.previousElementSibling);
});
}
var downLink = document.querySelectorAll(".down");
for (var i = 0; i < downLink.length; i++) {
downLink[i].addEventListener('click', function () {
var wrapper = this.parentElement;
if (wrapper.nextElementSibling)
wrapper.parentNode.insertBefore(wrapper.nextElementSibling, wrapper);
});
}
}
Example 2: how to move an element of an array in javascript
function moveElement(array,initialIndex,finalIndex) {
array.splice(finalIndex,0,array.splice(initialIndex,1)[0])
console.log(array);
return array;
}