Reputation: 832
my jquery code:
img[i]='img-src';
$("#popimage1").attr("src",img[i]);
alert($("#popimage1").width()); //doesn't give the width of the current image, but it gives for the previous, and for first null
my html code:
<img src="" id="popimage1"/>
so the concept is that i load different image src for each i with jquery,and then i do some calculations with the width and height. The problem is that i get the values for the image with the previous counter i. I have made a temporary solution, by putting
$("#popimage1").hide();
setTimeout(alert($("#popimage1").width(),2000);
$("#popimage1").show();
But its not working always, and causes an unnecessary timeout. instead of alert there is another function that uses img width and height, i just wrote alert for your convenience. Any help appreciated!
Upvotes: 5
Views: 6716
Reputation: 1498
Note that the .load
function has been deprecated since jQuery 1.8.
Use the .on
function with the corresponding event name:
$("#popimage1").on('load', function() {
alert($(this).width());
})
Reference: https://stackoverflow.com/a/40252711/2893053
Upvotes: 0
Reputation: 28762
You'll have to wait for the image to load first.
Try this.
img[i] = "img-src";
$("#popimage1").attr("src", img[i]).load(function() {
alert($("#popimage1").width());
});
Upvotes: 11
Reputation: 86882
Modifying the image source is asynchronous, therefore does not return immediately.
Try handling the load()
$("#popimage1").load(function() {
alert($(this).width());
});
Upvotes: 1