Skip to content Skip to sidebar Skip to footer

Drag Out Files From Browser Using Javascript

I'm trying to modify some code for dragging out files from your browser window I found here: http://www.thecssninja.com/javascript/gmail-dragout In my code I want to use for loops

Solution 1:

The problem does indeed start where you think it does

//I'm pretty sure the problem starts here.//If you substitue i for a specific element from the array and comment out the for loop, the script works just fine for the element specified.for(i=0; i<=file_count; i++) {
    files[i].addEventListener("dragstart",function(evt){
        evt.dataTransfer.setData("DownloadURL",fileDetails[i]);
    },false);
}

Basically your dragstart event listener is bound to i, which at the time of execution is the last element in the list.

The following will work better.

//I'm pretty sure the problem starts here.//If you substitue i for a specific element from the array and comment out the for loop, the script works just fine for the element specified.for(i=0; i<=file_count; i++) {
    files[i].addEventListener("dragstart", (function(idx) {
        returnfunction(evt){
           evt.dataTransfer.setData("DownloadURL",fileDetails[idx]);
        }
    })(i),false);
}

In the above code you will be creating and returning an object of type function with the correct value of i bound - essentially the closure is created at a different level and thus when accessed will get the correct data.

Post a Comment for "Drag Out Files From Browser Using Javascript"