Search code examples
jqueryjsondomimage-manipulation

How to add dimensions to dynamic img elements


I use a Json call to get a list of image addresses, then I add them individually to a div like this. Unfortunately the image dimension is not part of the Json information.

<div id="container">
   <img src="A.jpg" alt="" />
   <img src="B.jpg" alt="" />
   ...
</div>

Do any of you JQuery geniuses know of a code that would flawlessly and dynamically add the true Width and Height to each img element in the container as soon as each individual one is rendered?

I was thinking maybe the code could do a image width check width > 0 to evaluate when the image has actually been rendered, then fire. But I wouldn't know how to go about that and make it work stably. How is the best way of going about this?

Update, As the answers point out, adding Width or Height to the elements is pretty routine. The problem here is actually writing a code that would know when to do that. And evaluate that condition for each image not the page as a whole.

Update 2
I found a very nice working answer here


Solution

  • $('#container img').each(function(){
    var pic_real_width;
    var pic_real_height;
    
    $(img).load(function() {
        // Remove attributes in case img-element has set width and height
        $(this).removeAttr("width")
               .removeAttr("height")
               .css({ width: "", height: "" }); // Remove css dimensions as well
    
        pic_real_width = this.width;
        pic_real_height = this.height;
    });
    
    var src = img.src;
    img.src = "";
    img.src = src; // Triggers onload if image is cached
    });
    

    Credit goes to Xavi