Search code examples
javascriptjqueryhtmldrag-and-drop

How to transfer the whole element using html5 event.dataTransfer?


I want to remember or get data of the current drag element. This is what I did :

$('.source_element').on('dragstart', function(e){
   e.originalEvent.dataTransfer.setData("source", this); 
});

$('.destination').on('drop', function(e){
   var source = e.originalEvent.dataTransfer.getData('source');
   console.log(source);
   console.log(source.className);
   console.log($(source));
   $(this).html($(source).html());

   e.preventDefault();
});

The first console.log show [object HTMLDivElement] as a string, not an object, second undefined, third throws an error.

So I suspect that dataTransfer.setData only accept the data as a string, object is not allowed. If that's the case, how do you solve this problem, how can I remember which element is being dragged without knowing its specific ID ?


Solution

  • Just use some string to uniquely identify the element, like giving each element an id or a data attribute

    $('.source_element').on('dragstart', function(e){
       var id = 'drag-'+(new Date()).getTime();
       this.id = id;
       //$(this).attr('data-drag', id);
       e.originalEvent.dataTransfer.setData("source", id); 
    });
    
    $('.destination').on('drop', function(e){
       var source = e.originalEvent.dataTransfer.getData('source');
       console.log(source);
       console.log($('#'+source));
       $(this).html($('#'+source).html());
       //console.log($('[data-id="'+source+'"]'));
       //$(this).html($('[data-id="'+source+'"]').html());
    
       e.preventDefault();
    });