Paul
Paul

Reputation: 11746

Can I get the image height from jquery prior to displaying it?

I'm loading around 50 images from json data returned from PHP. To avoid the extra call of PHP getting the image size I'd like to do this on the client side. Is this possible?

Here's my current jquery call to build the image list:

// Create HTML for the images.
var html = '';

$.each(data.profiles, function() {

    // Can I determine the img height or do I need to wait until the image is loaded?

    html += '<a href="/view_profile.php?id='+this.user_id+'">';
    html += '<img src="'+this.file_name+'" width="200" height="" style="border:0;">';
    html += '</a><br>';

});

Upvotes: 1

Views: 84

Answers (2)

Gabe
Gabe

Reputation: 50493

You could bind the load event of the image and get it when the client loads the image like this:

$.each(data.profiles, function() {

    // Can I determine the img height or do I need to wait until the image is loaded?

    html += '<a href="/view_profile.php?id='+this.user_id+'">';

    var image = new Image();  
    image.src = this.file_name;
    image.onload = function() {
        var height = image.height;
    };

    var img = $("<img/>").css('border', 0).prop('src', image.src);
    html += img.wrap('<div></div>').html();
    html += '</a><br>';
});

Upvotes: 1

Abid Hussain
Abid Hussain

Reputation: 7762

try this:-

<img alt="photo-current" src="images/galleries/1/photo_1.jpg" id="photo-current"/>

<script type="text/javascript"> 
jQuery(document).ready(function($) {
      $("#photo-current").load(function() {
            var imageHeight = $(this).height();
            alert("image height " + imageHeight );
      });
});
</script>

Upvotes: 0

Related Questions