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
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());
});
});
.bind()
is out of date and should use .on()
instead. http://api.jquery.com/bind - Sparky 2012-04-04 18:29
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
var $imgs = $('img');
$imgs.load(function(){
console.log($(this).width());
});
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" />