Search code examples
jquerysrcattr

jquery get image width after src change


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!


Solution

  • 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());
    });