Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element width is undefined on document ready

I am trying to obtain an element width using the following code just before the </body>

<script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
        var diff = $('div.canvas img.photo').get(1).width;
        console.log(diff);
    });
</script> 

but it logs undefined. However, if I run $('div.canvas img.photo').get(1).width directly in the Chrome/Firebug console, it returns the correct width. The image is not being loaded with Javascript, so should be in place when the document ready fires. What am I doing wrong?

like image 290
Mild Fuzz Avatar asked Feb 21 '23 16:02

Mild Fuzz


1 Answers

No, it shouldn't. document.ready fires when all HTML has been loaded, but not the images. If you want to wait until all images are loaded, use window.load.

Example:

$(window).load(function(){
    var diff = $('div.canvas img.photo').get(1).width;
    console.log(diff);
});

Also, as some people have pointed out, you were attempting to get the property ".width" twice.

If at all possible, set a width on the imagetags in CSS. That way, you can safely use document.ready for your code. Using window.load will naturally delay the execution of your script, could be a second, could be ten, depending on the speed of the clients connection, and the amount of content on your page. This could cause unwanted jumps and jitters if you're performing any styling.

like image 94
Andreas Eriksson Avatar answered Mar 03 '23 10:03

Andreas Eriksson