0

I am resizing an image in JavaScript based on the current viewport size. No media queries and other such things, JS all the way, and no static sizes for elements.

So basically it looks something like this:

    var computedHeight = viewport.height * someRatio;
    var image = goog.dom.createDom('img', {
        'src': 'the.link.to.the.image',
        'height': computedHeight + 'px',
        'width': 'auto'
    };
flavian
  • 28,161
  • 11
  • 65
  • 105

3 Answers3

2

As the others said, you can't get the size before the image has been inserted into the document.

But you can calculate the size on your own.

When the image has been loaded, you may access the original size of the image. Based on this it's not very difficult to calculate the scaled size:

    var image = goog.dom.createDom('img', {
    'src': 'the.link.to.the.image',
    'height': computedHeight + 'px',
    'width': 'auto',
    'onload':function(){
      alert('width:'+
            Math.floor((this.naturalWidth*this.height)/this.naturalHeight)+
            '\nheight:'+this.height);        
    }
});
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
1

After the image has been displayed try querying the following properties

image.offsetWidth
image.offsetHeight
lostsource
  • 21,070
  • 8
  • 66
  • 88
  • check fiddle, is this what you're after? http://jsfiddle.net/KLfau/5/ (resize the panes so size changes and logging is triggered) – lostsource Nov 14 '12 at 19:22
  • If you use offsetWidth and offsetHeight after the images have been appended to the body and loaded, they should work – lostsource Nov 14 '12 at 19:27
1

Try goog.style.getComputedStyle(image, 'width'). Probably you'll need to add it to the document first.

Dmitry
  • 289
  • 1
  • 4