2
votes

so I followed an HTML5 drag and drop example here:

http://www.html5rocks.com/en/tutorials/dnd/basics/#toc-dataTransfer

and created the following code

http://jsfiddle.net/Vk5zT/

The problem is, I want to be able to essentially swap the entire element, and its data attributes, not just the inner html. How do I do this?

2

2 Answers

1
votes

You could just swap the elements themselves, not serializing and reparsing new elements.

        var parent = this.parentNode,
            insertionPoint, elem = this;

        do {
            elem = elem.nextSibling;
        } while (elem && elem !== draggedItem);

        insertionPoint = elem ? this : this.nextSibling;
        parent.insertBefore(draggedItem, insertionPoint);
        draggedItem = null;

http://jsfiddle.net/Vk5zT/11/

1
votes

See http://jsfiddle.net/Vk5zT/7/:

$(this).replaceWith($(draggedItem).clone(true,true));
$(draggedItem).replaceWith($(this).clone(true,true));

But .clone(true,true) should copy the event listeners too, but it doesn't, so drag and drop stops working. I solved it creating the function addEvents:

function addEvents(){
    $('.segmentListItem').each(function(index){
        $(this)[0].addEventListener('dragstart',handleDragStart,false);
        $(this)[0].addEventListener('drop',handleDrop,false);
        $(this)[0].addEventListener('dragover',handleDragOver,false);
    });
}

and then:

$(this).replaceWith($(draggedItem).clone(true,true));
$(draggedItem).replaceWith($(this).clone(true,true));
addEvents();

Edit:

I have fixed the problem with event listeners, and I have adapted your code to jquery:

http://jsfiddle.net/Vk5zT/12/