Skip to content Skip to sidebar Skip to footer

Getting Auto Size Of Img Before Adding It To Dom (using Jquery)

I'm dynamically adding IMG components to my DOM using JQuery, but depending on how big they are, I'll be adding them in different ways. Anyone have a good idea for getting the IMG

Solution 1:

DOM elements have dimensions only when added to a parent, as dimension is determined by the rendering engine. To go around this issue, have a <div> container absolutely positioned off screen, add the image to it first, get the dimension, then add the image at it's final destination.

Something like :

var _offscreen = $('<div></div>')
    .css({position:'absolute',left:'-999999px',width:'400px',height:'600px'})
    .appendTo($('body'));

var img = $('<img>/img>')
    .attr('src',"http://l1.yimg.com/a/i/ww/news/2011/03/25/zo.jpg")
    .load(function() {

      var $this = $(this);
      $this.appendTo(_offscreen);

      setTimeout(function() {
         var width = $this.width();
         var height = $this.height();

         alert($this.attr('src') + ' = ' + width + "x" + height);      
      }, 0);
});

** EDIT **

I just updated the code above. As it turned out, you need to let the rendering engine draw the image (of course!) and then get the dimension. So that edit works.

This could be put inside a convenient function like :

$('imageElement').loadImage("path/to/image", function() {
   alert("Image " + $(this).attr('src') + " loaded: " + $(this).width() + "x" + $(this).height());
});

** UPDATE **

I thought you might like to see the code above put into a JQuery plugin... just for fun :) It just works, there is no validation done (i.e. it won't check if you pass other elements than <img>), and if the selector returns more than one element, the plugin will load the same image into each selected elements. You could actually have the plugin argument url be an array (optional) and load each image of the array in each selected element, etc. Just a thought.

Solution 2:

You should be able to do this without appending the image to the DOM. Kristoffer (hey that's my name too!) is on the right track but the image needs to be loaded before you can try to read the width / height.

var getImageSize = function(src) {
    var img = newImage();
    $(img).bind('load', function(e) {
        var height = img.height;
        var width = img.width;
        document.write('width:' + width + ', height: ' + height);
    });
    img.src = src;
};

getImageSize('http://farm4.static.flickr.com/3261/5791911248_b777cb1dde_b.jpg');

Demo here: http://jsfiddle.net/H3p97/

Post a Comment for "Getting Auto Size Of Img Before Adding It To Dom (using Jquery)"