Search code examples
javascriptdrag-and-dropevent-handling

file data not getting passed on js drop event


I have several methods in a class. Class instances are being dynamically created. One of the instances adds an event listener to the 'drop' event. That drop event listener function is supposed to pass the image data to handleDrop() in the class instance, but I'm getting cannot read property 'dataTransfer' of undefined at the dt = e.dataTransfer, line of the handler function.

I'm trying to follow https://soshace.com/the-ultimate-guide-to-drag-and-drop-image-uploading-with-pure-javascript/

data listener code

    canvasWrapper.addEventListener('drop', canvasContext.preventDefault, false);
    canvasWrapper.addEventListener('drop', function () {
        canvasContext.handleDrop(this.event), false;

    });

handler function

handleDrop(e) {
    let dt;
    console.log('we have a drop');
    dt = e.dataTransfer,
        console.log('dt', dt);
    files = dt.files;

Complete code is at https://github.com/tnewhook/CartoonBuilder/blob/master/cartoonBuilder.js


Solution

  • The answer was pretty simple: I needed to combine the two lines in handleDrop() into files = e.dataTransfer.files,. For some reason it liked the single var instead of two.