2

I am trying to get the actual width of an image...here is the image in question

<img src="upload/<?php echo $array['image'] ?>" height="200" class="active" />

and this what I have tried in jQuery

$(window).bind('load', function() {  
    var img_width = $("#slideshow").find("img").width();
    $("#slideshow img").css("width", img_width);
    alert(img_width);
});

the alert returns 255 for every images i've tried this with, which is the width of the div slideshow. with the height of these images all being 200 they will have different widths, my question is, how do I get these widths?

Thanks, J

user1274810
  • 119
  • 1
  • 4
  • 10
  • check this might have been answered already: http://stackoverflow.com/questions/2395931/how-do-i-get-actual-image-width-and-height-using-jquery – sakhunzai Apr 04 '12 at 18:22

4 Answers4

1

This should populate an array with the widths of all your images:

$(window).bind('load', function() {  
    var img_widths = [];
    var imgs = $("#slideshow").find("img");
    imgs.each(function() {
      img_widths.push($(this).width());
    });
});
JoshNaro
  • 2,015
  • 2
  • 22
  • 37
0

If #slideshow contains more than one img, your call to $("#slideshow").find("img").width(); will only return the first img width, which in this case, must be 200

nathanjosiah
  • 4,253
  • 4
  • 33
  • 46
0
var $imgs = $('img');
$imgs.load(function(){
    console.log($(this).width());
});
thecodeparadox
  • 81,835
  • 21
  • 131
  • 160
0

I'm going to give you the answer you didn't ask for - but what I think is the better solution.

Only because I see you are using PHP in the image itself - why not just write the imagesize info with PHP. Its better and doesn't wait for load.

<?php 
// path from document root seems to work best for me
list( , , , $attr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . "/upload/".$array['image']);
?>
<img src="upload/<?php echo $array['image'] ?>" <?php echo $attr; ?> class="active" />
mikevoermans
  • 3,807
  • 18
  • 27
  • that gets the size of the actual image from the server, what I am looking for the width of the image when the height is 200 – user1274810 Apr 04 '12 at 18:49