Google Chrome is doing things wrong again

Posted by Stefan Liebenberg on Stack Overflow See other posts from Stack Overflow or by Stefan Liebenberg
Published on 2010-06-14T07:38:18Z Indexed on 2010/06/14 7:42 UTC
Read the original article Hit count: 189

Filed under:
|
|
|

Chrome is wrongly reporting width and height values for images during, or just after, load time. Jquery is used in this code example:

<img id='image01' alt='picture that is 145x134' src='/images/picture.jpg' />

<script>
 var img = $( 'img#image01' )

 img.width() // would return 145 in Firefox and 0 in Chrome.
 img.height() // would return 134 in Firefox and 0 in Chrome.
</script>

If you put the script in a onload function, the result is the same. but if you run the code a few seconds after the page has loaded, chrome returns the correct result.

<script>
  function example () {
    var img = $( 'img#image01' );

    img.width() // returns 145 in both Firefox and Chrome.
    img.height() // returns 134 in both Firefox and Chrome.
  }
  window.setTimeout( example, 1000 )
</script>

Also if you specify the width and height values in the img tag, the script seems to work as expected in both Firefox and Chrome.

<img id='image01' src='/images/picture.jpg' width=145 height=134 />

But as you cannot always control the html input, this is not an ideal workaround. Can jQuery be patched with a better workaround for this problem? or will I need to specify the width and height for every image in my code?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery