Marcos R. Guevara Marcos R. Guevara - 6 months ago 8
Javascript Question

Why is executing two times?


This was solved, check the solution by DBS


I'm trying to create a drop input like mediafire. I'm having an issue with a function that repeats two times.

The message from browser console:

se ejecuta la funcion file:13:3
File { name: "8b32cacb0ad946479513721142c7fc9f.jp…", lastModified: 1447114071000, lastModifiedDate: Date 2015-11-10T00:07:51.000Z, size: 161020, type: "image/jpeg" } file:18:7
fin de bucle file:30:5
se ejecuta la funcion file:13:3
File { name: "8b32cacb0ad946479513721142c7fc9f.jp…", lastModified: 1447114071000, lastModifiedDate: Date 2015-11-10T00:07:51.000Z, size: 161020, type: "image/jpeg" } file:18:7
fin de bucle file:30:5


Code

script.
var dropZone = document.getElementById('dropZone');
dropZone.addEventListener("drop", drop, false);
var miniatures = document.getElementById("miniatures");
var miniature = document.createElement("div");
miniature.className = "all-20";
var img = document.createElement("img");
var files;
var reader = [];

// mecanica
function drop(e){
console.log("se ejecuta la funcion");
var dt = e.dataTransfer;
files = dt.files;
for (var i = 0; i < files.length; i++){
var file = files[i];
console.log(file);
img.file = file;
miniature.appendChild(img);
miniatures.appendChild(miniature);
reader[i] = new FileReader();
reader[i].onload = (function(event){
return function(e){
event.src= e.target.result;
};
})(img);
reader[i].readAsDataURL(file);
}
console.log('fin de bucle');
}


HTML

form(action="" enctype="multipart/form-data")
input(class="all-100 drop ink-droppable align-center fallback" type="file" multiple="multiple" id="dropZone" ondrop="drop(event)")

DBS DBS
Answer

You're attaching the drop event twice, once in the HTML and once in the JS.

Remove one of these:

ondrop="drop(event)"

or

var dropZone = document.getElementById('dropZone');
dropZone.addEventListener("drop", drop, false);