2

I have an image thats height is 100% of the browser and width is auto. So the width can vary depending on the picture and the resolution of your screen.

So, I want to calculate the width in the browser thats not taken up by the image.

.main-image img {
    width:auto
}

var winheight = $(window).height();

$('.main-image img').css('height', winheight);

So, I was thinking about doing something like this but it wont work.

   var findimage = $('.main-image img');
   var imagewidth = findimage.clientHeight;
   console.log("image width is " + imagewidth);

However, this returns "image width is undefined". What should I do?

Pbk1303
  • 3,702
  • 2
  • 32
  • 47
Alain Goldman
  • 2,896
  • 5
  • 43
  • 75

2 Answers2

3

Remember that an image is not part of the markup, so it has to load before you can retrieve it's width.

$('.main-image img').onload(function () {
    console.log("image width is " + $(this).width());
});
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • I would say that you can probably just do `this.width` onload. No reason to create a jQuery object unless you have another use for that. But this is definitely correct. – kalley Aug 03 '13 at 03:39
  • @kalley You are correct, `this.width` would work and it would be more efficient because it doesn't have to be interpreted by the jQuery plugin. – federico-t Aug 03 '13 at 03:41
  • Uncaught Type error: object [object Object] has no method 'onload' – Alain Goldman Aug 03 '13 at 03:43
1

Try using

$('.main-image img').width()
$('.main-image img').height()

and use Offset for positioning Left/Top

Cody Guldner
  • 2,888
  • 1
  • 25
  • 36