From bd911766eed2585fc415d8ae1aed8d83ea74c476 Mon Sep 17 00:00:00 2001 From: Mike Date: Thu, 23 Jun 2016 18:55:50 -0700 Subject: [PATCH] When drage, Swap Elements instead of moving them This fixes this problem: https://github.com/RubaXa/Sortable/issues/869 --- Sortable.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/Sortable.js b/Sortable.js index d6f04237f..41b3943de 100644 --- a/Sortable.js +++ b/Sortable.js @@ -683,11 +683,31 @@ } if (!dragEl.contains(el)) { - if (after && !nextSibling) { - el.appendChild(dragEl); - } else { - target.parentNode.insertBefore(dragEl, after ? nextSibling : target); - } + swapElements(dragEl, target); + + function swapElements( /** DOM */ obj1, /** DOM */ obj2, /** DOM */ obj1Parent, /** DOM */ obj2Parent) { + // save the location of obj2 + var parent1 = obj1Parent || obj1.parentNode; + var parent2 = obj2Parent || obj2.parentNode; + var next2 = obj2.nextSibling; + // special case for obj1 is the next sibling of obj2 + if (next2 === obj1) { + // just put obj1 before obj2 + parent2.insertBefore(obj1, obj2); + } else { + // insert obj2 right before obj1 + parent1.insertBefore(obj2, obj1); + + // now insert obj1 where obj2 was + if (next2) { + // if there was an element after obj2, then insert obj1 right before that + parent2.insertBefore(obj1, next2); + } else { + // otherwise, just append as last child + parent2.appendChild(obj1); + } + } + } } parentEl = dragEl.parentNode; // actualization