2

I have a list of nodes that I'm able to drag and drop.

<ul id="container">
<li id="item_1">Item 1</li>
<li id="item_2">Item 2</li>
<li id="item_3">Item 3</li>
<li id="item_4">Item 4</li>
<li id="item_5">Item 5</li>
<li id="item_6">Item 6</li>
</ul>

I can click and drag #item_5 over on top of #item_2 and on "drop", I can return the source (#item_5) and the item getting dropped on (#item2)

How would I insert the dropped item (#item_5) before the target (#item_2), then adjust each node after Item 2 back one position? I need help with a method to perform this task

e.g.

function movebefore(a, b) {...}

(Please assume javascript frameworks like jQuery cannot be used)

The actual code: http://jsfiddle.net/danmasq/BkNAF/

2 Answers 2

2

dropNode is the drop target
dragNode is the node being dragged
you mentioned you had both available.

var movebefore = function( dragNode , dropNode ) {

    dropNode.parentNode.insertBefore( dragNode , dropNode );

}
Sign up to request clarification or add additional context in comments.

Comments

1
function movebefore(a, b) { // If "a" is the node you're dragging and "b" is the node on top of which you dropped "a"
    b.parentNode.insertBefore(a, b); // Or "b.nextSibling", depending on what you want to do
}

It's that simple! The DOM will take care of removing the element from its previous position and adjusting the other elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.