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.
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);
};