0

I am trying to get my image width and height by using the following code but all I receive is undefined.

Can anyone explain to me how this work?

<script>
var img = new Image();
img = document.getElementById("top");
alert(this.width + 'x' + this.height);
</script>
<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg"/>
        </div>
    </div>
</body> 
Markus Hayner
  • 2,869
  • 2
  • 28
  • 60

8 Answers8

5

First, if you're getting the image from the document, you don't need to call new Image.

You do need to wait until the img element exists, and until the img loads.

That's easiest if you add the image with the script, and hook the load event before setting src:

<body>
    <div id="ad">
        <div id="banner"></div>
    </div>
<script>
var img = document.createElement('img')
img.className = "top";
img.id = "top";
img.onload = function() {
  alert(this.width + 'x' + this.height);
};
img.src="frame_2.jpg";
document.getElementById("banner").appendChild(img);
</script>
</body>

You can do it with the image in the HTML, though, you just have to allow for the possibility the image may have already loaded before you hooked the event:

<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg"/>
        </div>
    </div>
<script>
var img = document.getElementById("top");
img.onload = loaded;
if (img.complete) {
    loaded();
}
function loaded() {
  if (img) {
      alert(img.width + 'x' + img.height);
      img.onload = null;
      img = null; // Just as a marker in case of repeated calls
  }
};
</script>
</body>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

this will most probably point to Window in that case. Try img.width and img.height instead.

Kamen Minkov
  • 3,324
  • 1
  • 14
  • 21
  • 1
    or `img.clientWidth` and `img.clientHeight` if you want the responsive height and widths. – ThisClark Nov 05 '15 at 15:47
  • 1
    Not to mention the superfluous `new Image()` and not waiting for the image to render, much less load. Ugh. – Luaan Nov 05 '15 at 15:49
2

Try this:

img = document.getElementById("top");
img.onload = function() {
  alert(img.width + 'x' + img.height);
};
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="http://fpoimg.com/300x300"/>
        </div>
    </div>
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Worth noting that the script tag needs to come *after* the `img` or else wait for `DOMContentReady` (otherwise `getElementById` will return `null`). – Sean Vieira Nov 05 '15 at 15:48
  • 1
    This will be a race the code will sometimes lose, particularly if the image is in cache. – T.J. Crowder Nov 05 '15 at 15:49
0

You can get this with clientWidth and clientHeight.

var width = img.clientWidth;
var height = img.clientHeight;

See clientWidth and clientHeight

morels
  • 2,095
  • 17
  • 24
camelCase
  • 5,460
  • 3
  • 34
  • 37
0

You don't need to create an instance of Image if later you re-assign that variable with an element queried on the DOM...

By the way, you need to wait the Dom Ready or Window Loaded (indicated for media objects) event...

document.addEventListener('DOMContentLoaded', function() {
  var img = document.querySelector('.my-image');

  document.querySelector('#result').innerHTML = img.width + ' x ' + img.height;
});
<h1 id="result"></h1>

<img src="http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg" class="my-image" />
Hitmands
  • 13,491
  • 4
  • 34
  • 69
  • Need to add `img.onload` and do your write there - the image hasn't necessarily loaded when `DOMContentLoaded` fires. (I see `0 x 0` in the example right now). – Sean Vieira Nov 05 '15 at 15:54
  • As I worte below, for media-objects (such as images, videos, ecc.) the window.onload event is more correct... If you attach an event to a single image this doesn't work with more images... the global window event works fine! – Hitmands Nov 05 '15 at 15:59
0

I am trying to get my image width and height by using the following code but all I receive is undefined.

This because you try to select the image in the DOM before it has been created.

If you want to get image dimensions you can do many ways. If you want simply check them you can do inline:

<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg" onload="console.log(this.width + ' x ' + this.height + ' px');"/>
        </div>
    </div>
</body> 
morels
  • 2,095
  • 17
  • 24
0

CSS and other style - may change result of question.

Use attributes: naturalWidth and naturalHeight

They give correct imagesize.

Lyusten Elder
  • 3,213
  • 1
  • 14
  • 10
-2

Why not to try simple jQuery?

var imageWidth = $('#top').width();
var imageHeight = $('#top').height();
alert(imageWidth + 'x' + imageHeight);
markoffden
  • 1,406
  • 1
  • 15
  • 31