jQuery pass element to dataTransfer property

technopeasant picture technopeasant · Apr 2, 2013 · Viewed 12.6k times · Source

Trying to pass a jQuery object to the dataTransfer property during a drag/drop sequence. After adding the property to jQuert.event.props array I'm able to assign it, but it returns undefined on during the drop event. Not sure what I'm missing here- seems really straightforward.

Javascript:

function dragClip(clip, event){

    event.dataTransfer.el = clip;

    /* Console confirms event.dataTransfer.el is the jQuery object */
}

function dropClip(target, event){

    target.append(event.dataTransfer.el);

    /* event.dataTransfer.el no longer has the object... where'd it go?? */
}

jQuery.event.props.push('dataTransfer');

$('#titles')
    .bind('dragenter dragover', false)
    .bind('drop', function(event){

        dropClip($(this), event);
    });

$('.clip').bind('dragstart', function(event){

    dragClip($(this), event);
});

UPDATE:

Rewritten to remove the verbosity. Had included other stuff in there, but an anonymous function will do just fine:

jQuery.event.props.push('dataTransfer');

$('#titles')
    .bind('dragenter dragover', false)
    .bind('drop', function(event){

        $(this).append(event.dataTransfer.el);
    });

$('.clip').bind('dragstart', function(event){

    event.dataTransfer.el = $(this);
});

UPDATE

As per @barney's final answer, my final working code. I noticed that using the original event didn't allow me to pass an object as data, so instead I applied the ID and rebuilt the jQuery object on drop. Also tightened everything up by getting rid of the declared functions. Less code, same result.

$('#titles')
    .bind('dragenter dragover', false)
    .bind('drop', function(event){

        $(this).append($('#' + event.originalEvent.dataTransfer.getData('clip')));
    });

$('.clip')
    .bind('dragstart', function(event){

        event.originalEvent.dataTransfer.setData('clip', $(this).attr('id'));
    });

Answer

Barney picture Barney · Apr 2, 2013

Personally, I try to play with jQuery internals as little as possible and extract the original event object where possible. When using drag and drop in the past, I've always made use of event.originalEvent.dataTransfer.