Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get image width after src change

Tags:

jquery

attr

src

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!

like image 788
user666 Avatar asked Nov 14 '11 20:11

user666


People also ask

How to get the width of image in jQuery?

var imageWidth = $(Imgsize). width();

How to get width of image in JavaScript?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.

How to get image size from URL in jQuery?

one('load',function(){ orgWidth = tmpImg. width; orgHeight = tmpImg. height; alert(orgWidth+"x"+orgHeight); }); The above code will gets the image dimension.

How to set width image HTML?

If your image doesn't fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.


2 Answers

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());
});
like image 175
Michael Mior Avatar answered Oct 18 '22 16:10

Michael Mior


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

Try handling the load()

$("#popimage1").load(function() {
  alert($(this).width());
});
like image 42
John Hartsock Avatar answered Oct 18 '22 16:10

John Hartsock