Search code examples
javascriptmootools

image dimensions in javascript


I'm trying to get the dimensions of an image using javascript-- Mootools is the loaded library.

However, even though I get the image element with no problem, and see in the element's properties a valid width and height, the height value is always returned as 0 when I try to access the property.

Why?

window.addEvent("domready", function(){
    var thisImg = $$("img.myimgclass");

    console.dir(thisImg[0]); // prints all image data, including width AND height values

    var height = thisImg[0].height;
    var width = thisImg[0].width;

    console.log(height); // prints 0 even though thisImg shows a valid height set
    console.log(width); // prints valid width

});

Solution

  • You'll need to call your code in the window load event, because even if the dom is built that doesn't mean the image is loaded. The console shows live objects, that is by the time you look at the console the image has loaded but when it was logged is hadn't loaded yet.