jQuery - get the width of an image

Go To StackoverFlow.com

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

2012-04-04 18:19
by user1274810
check this might have been answered already: http://stackoverflow.com/questions/2395931/how-do-i-get-actual-image-width-and-height-using-jquer - sakhunzai 2012-04-04 18:22


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());
    });
});
2012-04-04 18:26
by JoshNaro
.bind() is out of date and should use .on() instead. http://api.jquery.com/bind - Sparky 2012-04-04 18:29
ummm, this doesnt appear to apply to my image - user1274810 2012-04-04 18:31
http://getfirebug.com - JoshNaro 2012-04-04 18:53


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

2012-04-04 18:22
by nathanjosiah


0

var $imgs = $('img');
$imgs.load(function(){
    console.log($(this).width());
});
2012-04-04 18:29
by thecodeparadox
when I inspect the element, the width attribute does not appear : - user1274810 2012-04-04 18:34


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" />
2012-04-04 18:37
by mikevoermans
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 20 - user1274810 2012-04-04 18:49
Ads