0

To get the dimensions of an image object, I need to use javascript on my page.

When I console.log the image object ($img), I get something like this:

[<img src="/path/to/image/">]

I want to get the original height and width of the original image. I tried using .naturalWidth, .width but those gave strange results.

Can anyone help me out?

B_s
  • 3,026
  • 5
  • 32
  • 51
  • Are you sure your $img is a correct jquery object. looks more like a simple string to me. – Stijn Bernards Jan 28 '15 at 16:14
  • It isn't jquery, it looks like it is plain javascript – B_s Jan 28 '15 at 16:14
  • In your logged output, `$img` appears to be an array. – Brennan Jan 28 '15 at 16:15
  • "those gave strange results" can you explain? how did you get the image object? can you show your full code? – atmd Jan 28 '15 at 16:17
  • I cannot share much more code, since it is spread out over multiple documents and classes. Strange results were things like a bunch of DOM text – B_s Jan 28 '15 at 16:19
  • Have you tried in this way http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome – Anand Gangadhara Jan 28 '15 at 16:20
  • @AnandGangadhara I cannot change the creation of the object, I just need to get its dimensions – B_s Jan 28 '15 at 16:21
  • Let me ask it in another way: there is an `img` tag on my page in a unique parent. How do I get the dimensions of this image? – B_s Jan 28 '15 at 16:22
  • I just want to confirm why is naturalHeight is not working for you, please check this its working here http://jsfiddle.net/cztprdv0/ or like this http://jsfiddle.net/gzqjrbt7/ – Anand Gangadhara Jan 28 '15 at 16:26
  • @AnandGangadhara when I use `.naturalHeight` on the `$img` I get `undefined` – B_s Jan 28 '15 at 16:32
  • What browser are you using to look at your console? – Daniel Jan 28 '15 at 16:41
  • @Daniel Safari and Chrome, but I think something else is going on. I'm not very strong with javascript objects, so I'm having a hard time finding the problem ... – B_s Jan 28 '15 at 16:42

2 Answers2

1

It is said that webkit may need to load the image first. To do this apply the onload first.

$img[0].onload = function() {
    console.log(this.naturalWidth);
}
Daniel
  • 4,816
  • 3
  • 27
  • 31
  • Yeah I don't use things like `document.getElements` ... to find the image. I simply get an image **object** and I have to get the dimensions – B_s Jan 28 '15 at 16:29
  • ah ... I see you got it. I was pointing out the array position, but I know how easy a detail can be missed at times ... :-) .. Good luck. – Daniel Jan 28 '15 at 17:01
  • Your answer made me try the array position and helped me solve the issue. Upvote for that, thanks :) – B_s Jan 28 '15 at 17:28
0

With your help I got on the right track and solved my problem.

Instead of using:

$img.naturalHeight

I should have been using:

$img[0].naturalHeight

Thanks everyone!

B_s
  • 3,026
  • 5
  • 32
  • 51