The problem is that ths
is not a local variable.
So, for every element processed by .each
, the same global property (window.this
) is re-assigned. The last time it is assigned, it refers to "image3" - and thus all the asynchronous onload
events, which occur later, will refer to "image3".
The quickest fix is to add var
and change the code to:
var ths = $(this);
This makes ths
a local variable, which will be distinct for each element processed by .each
(as each element is processed in a new function scope), that is bound in the closure formed by the onload
callbacks.
Here is a working fiddle (thanks, Ani!)