Reputation: 575
Suppose this html:
<img src="thumbnail/img.png">
<div class="frame">
</div>
Thumbnails lie in their own directory called thumbnail
, while the regular size images they refer to are to be found in regular
. The thumbnails are attached an event listener which behaves like this on click (being e
the event passed as parameter):
var src = $(e.target).attr("src");
var path = "regular/" + src.slice(src.lastIndexOf("/") + 1);
So what I put into the variable path
in this case is regular/img.png
. Next I want frame
to take the image at path
as background and adapt its size to it, but something strange happens:
var image = new Image();
image.src = path;
console.log(image.width); // weirdness starts here
// same behavior with .naturalWidth
I'd expect the console to show image
's width, but what I get is a 0
. Only at the first click though: any further click yields the correct value.
Why is that?
Upvotes: 1
Views: 711
Reputation: 1258
It's simply because the image hasn't loaded yet. You'll need to register an event listener like this before you set the "src" attribute (and not after, because as soon as you set the "src", it will start loading the file) and then do your stuff within the callback function:
var image = new Image();
image.addEventListener("load", function() {
console.log(image.width);
}, false);
image.src = path;
NOTE: This is plain javascript, and therefore does not rely on any external libraries; you could also use the jQuery load
function, or something similar, to achieve the same effect, if you prefer.
Upvotes: 2