1
I want to generate thumbnails of images that the user selects. My problem is that always one of the images generates 3 thumbnails
Demo here: http://jsfiddle.net/gTLXp/
1
I want to generate thumbnails of images that the user selects. My problem is that always one of the images generates 3 thumbnails
Demo here: http://jsfiddle.net/gTLXp/
6
You must not use for .. in
to iterate over arrays (or array-Likes). It is used to iterate over the properties of an object. As its FileList
has three properties ("0"
, "length"
and "item"
) the code will run three times.
Replace with a for
common:
for (var key = 0 ; key < files.length ; key++)
Interestingly, solving the problem is even easier by using ES6: http://jsfiddle.net/PqppL/
I thought the 14,15 and 16 lines of the example could take care of that, but I realized now that even when I do 'files.item("anything")' an image is returned.
@Gustavorodrigues True. Do you know how well supported ES6 is in current browsers? I couldn’t find any information in caniuse.com
I’m not talking about current support, but that ES6 solves the problem of for in
with arrays so easily. Support? I think only Firefox.
@Lucasmarçaldossantos strange... must be a bug. Documentation of FileList.item
clearly asks for a numerical index. In fact, I will update my answer because it only works because of this bug :P
@Gustavorodrigues Your example worked perfectly on Chrome.
You must have some flag on your Chrome, for me gives syntax error even in Canary.
@bfavaretto ops, my fault. In fact it gives syntax error with me too (I must have looked at the code of one fiddle, but executed the other)
@bfavaretto I follow the Chrome updates blog even using Firefox, waiting for the day they will support ES6, hyphenation and other things. Even Nodejs can’t stand it, I have to keep using the Altjs for simple things like .map((el)=>el[1])
.
2
The problem is the use of for (... in ...)
, which also reads the file array properties, such as length
. That is, you are adding an image when the length property is iterated!
EDIT A help to generate Thumb:
Just to supplement the answer, you can resize the element img
in order to maintain the proportions of the original image by setting the following style for it:
max-width: 20px; /* qualquer largura máxima desejada */
width: auto;
height: auto;
Browser other questions tagged javascript html5
You are not signed in. Login or sign up in order to post.
In my case it generated four, I get a bonus for it?
– Gustavo Rodrigues