Q: Why can I not get correct width and height of an image via Javascript in Chrome?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. Later I finally found out why. Read on to learn how I solved it.
AnswerIf 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 make sure either of the following:
* The <img> tag has width and height specified as attributes or via CSS, or if you prefer...
* Use
$(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.
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. I am not sure why. Anyone care to enlighten me?
Kamis, 24 Februari 2011
Langganan:
Posting Komentar (Atom)
0 komentar:
Posting Komentar