Feb 24, 2011

f Comment

HTML <img> Tag Issue In Google Chrome and How to Solve it!

Amazon Why can I not get correct width and height of an image via Javascript in Google Chrome web browser? Read on to find out why and how to solve this issue!

On my other website Men's Fashion For Less I use a lot of jQuery plugins. I used http://www.smoothdivscroll.com/ to auto scroll a bunch of photos and to my surprise Chrome is not handling the scrolling image functionality correctly. Read on to learn how I solved it!

If you use jQuery a lot in a website and are currently trying to validate your website in Chrome, you may be surprised that it's not handling images the same way Internet Explorer and Firefox are via javascript. Basically if you are trying to get the width or height of an image via javascript or jQuery like the following:

var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

You need to do one of the following things.

1st Thing
The <img> tag needs to have width attribute and height attribute, or they can be set via CSS script. Here's an example:

<img src='[whatever source]' width='100' height='100'/>
2nd Thing
The Javascript code to extract width and height needs to be inside

$(window).load(function() {...})
instead of

$(document).ready(function() {...})
So that the Chrome can successfully detect the width and height of an image once it's loaded.

Why Does Google Chrome Have This Problem?
This is due to the fact that Chrome is a Webkit browser (same issue applies to Safari) and for some reason you need to explicitly tell Chrome the height and width of an image if you want to be able to access them via javascript. Internet Explorer and Firefox are able to detect the dimension of an image without you having to do the above.

If you have any questions let me know and I will do my best to help you!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael