jquery get image width after src change
Asked Answered
F

3

5

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!

Felice answered 14/11, 2011 at 20:16 Comment(3)
possible duplicate of Get real image width and height with Javascript in Safari/Chrome?Luanaluanda
Have you tried using the answer there? It should serve your purposes.Luanaluanda
well the question is a bit different but the first answer solves my problem ,now i see it again.. but i didn't realise it first time, anyway i think it will be good not to lock the topic since the question is alittle different.. thank you all!Felice
R
11

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());
});
Rumpf answered 14/11, 2011 at 20:18 Comment(0)
P
1

Modifying the image source is asynchronous, therefore does not return immediately.

Try handling the load()

$("#popimage1").load(function() {
  alert($(this).width());
});
Pau answered 14/11, 2011 at 20:19 Comment(0)
H
0

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://mcmap.net/q/92171/-quot-uncaught-typeerror-a-indexof-is-not-a-function-quot-error-when-opening-new-foundation-project

Husky answered 6/5, 2021 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.