0

I'm working on a lightbox, and I need to get the native dimensions of an image element to be displayed. I'm working on a method based off this tutorial by CSS-Tricks. My picture is 400x400 pixels natively, but my method keeps returning 0x0. Here's the relevant code:

    function setLuxboxSize () {
    console.log("picture original: " + luxpic.attr('src'));

    var testingImage = new Image();

    testingImage.src = luxpic.attr('src');

    //console.log('testingImage src:' + testingImage.attr('src'));


    var picWidth = testingImage.width;
    var picHeight = testingImage.height;


    console.log("original width: " + picWidth);
    console.log("original height: " + picHeight);
};

Also, when the commented out console.log line is active, I get the following error in console : Uncaught TypeError: Object # has no method 'attr'. The first console.log line returns a src as expected. What am I doing wrong?

EDIT: Problem was the image wasn't loaded yet, and width and height calls won't return the correct value until it is. Check LorDex or Satpal's answers for using the onload function to get the dimensions.

Ber
  • 695
  • 1
  • 11
  • 17
  • What is the `luxpic` var? Your code is expecting it to be a wrapped jQuery result, like `var luxpic = $("#image");` – Will Feb 07 '14 at 23:55
  • Oh yeah that stuff is defined elsewhere, I didn't out that part up though :) – Ber Feb 08 '14 at 00:02

2 Answers2

1

You can check actual image size after it's been loaded. In order to do this, use .onload() method:

testingImage.onLoad(function() {
    var picWidth = testingImage.width;
    var picHeight = testingImage.height;
    console.log("original width: " + picWidth);
    console.log("original height: " + picHeight);
});
LorDex
  • 2,591
  • 1
  • 20
  • 32
0

You will have to load the image first then you can check its dimensions.

var testingImage = new Image();
testingImage.src = luxpic.attr('src');
testingImage.onload = function () { 
    var picWidth = this.width;
    var picHeight = this.height;

    console.log("original width: " + picWidth);
    console.log("original height: " + picHeight);
};
Satpal
  • 132,252
  • 13
  • 159
  • 168