Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

img isn't being loaded on DOM ready. docs:

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

change to this:

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

Image's width would only be available when its loaded completely. jQuery supports onload event on every images too.

You can use,

$('div.canvas img.photo').load(function(){
  // here the image (or all images which match selector) has been loaded.
}

The problem is that your image is not loaded yet when you try to get its dimentions. To make it work wrap your code into $(window).load. Or another option. If you know the sizes of the image you can provide width and height attributes, then it's going to work even inside DOMContentLoaded. Sometimes it's preferable because onload event takes longer to fire then 'DOMContentLoaded'. Otherwise you would need to use $(window).load, see @Andreas Carlbom answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top