Wes
Wes

Reputation: 35

Why can't I get the naturalHeight/naturalWidth of an image in javascript/JQuery?

So I'm trying to do some very basic div re-sizing based on the properties of the image contained within it. I know I can do something really basic like set the background an padding around the image and achieve the same effect, but this is sort of a personal challenge.

The problem I am having is that when I try to fetch the naturalHeight or naturalWidth values of the image, I get a value of 0. However, when I try to fetch these values using the console, they return the correct values. Also, my resizeDiv() function is coming up as undefined in console.

Here's the code:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>kitten_resize - WesGilleland.com</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
    var kittens = new Array("100x100_kitten.jpeg","150x150_kitten.jpeg","200x150_kitten.jpeg");

    $('#kittens').attr('src', kittens[0]); //set the image

    function resizeDiv() {
        var img = document.getElementById('kittens');
        var imgH = img.naturalHeight;
        var imgW = img.naturalWidth;
        $('div').width(imgW);
        $('div').height(imgH);
        console.log('Current imgH: '+imgH);
        console.log('Current imgW: '+imgW);
    };

    resizeDiv();

});
</script>

<style>
div {
    background-color: black;
    padding: 10px;
    margin: auto;
}
</style>
</head>

<body>
<div>
<img id="kittens" src='' />
</div>
</body>
</html>

You can also find a working copy here: http://www.wesgilleland.com/projects/kitten_resize/

I feel like it's something very basic that I'm missing; I haven't fiddled with this stuff since my associate's degree a year ago. Thanks to anyone who can help!

Upvotes: 2

Views: 9138

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

That's because your image isn't yet loaded when you read the original dimensions.

You should read the dimensions when the image is loaded :

 var img = $('#kittens')[0];
 img.onload = resizeDiv;
 img.src = kittens[0];

Upvotes: 6

Related Questions