I am creating a jQuery plugin.
How do I get real image width and height with Javascript in Safari?
Following works with Firefox 3, IE7 and Opera 9:
var pic = $("img")
// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");
var pic_real_width = pic.width();
var pic_real_height = pic.height();
But in Webkit browsers like Safari and Google Chrome values are 0.
Another suggestion is to use imagesLoaded plugin.
There is now a jQuery plugin,
event.special.load
, to deal with cases where the load event on a cached image doesn't fire: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.jsYou don't need to remove style from the image or image dimensions attributes. Just create an element with javascript and get the created object width.
The root problem is that WebKit browsers (Safari and Chrome) load JavaScript and CSS information in parallel. Thus, JavaScript may execute before the styling effects of CSS have been computed, returning the wrong answer. In jQuery, I've found that the solution is to wait until document.readyState == 'complete', .e.g.,
As far as width and height goes... depending on what you are doing you may want offsetWidth and offsetHeight, which include things like borders and padding.
To add to Xavi's answer,
Paul Irish's githubDavid Desandro's gitgub offers a function called imagesLoaded() that works on the same principles, and gets around the problem of some browser's cached images not firing the .load() event (with clever original_src -> data_uri -> original_src switching).It's is widely used and updated regularly, which contributes to it being the most robust solution to the problem, IMO.
I use different approach, simply make Ajax call to server to get image size when image object is in use.
and of course server side code: