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.
// This code helps to show image with 200*274 dimention
Use the
naturalHeight
andnaturalWidth
attributes from HTML5.For example:
Works in IE9+, Chrome, Firefox, Safari and Opera (stats).
My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).
Anyway, Safari keeps the dimensions of the previous image so the dimensions are always one image behind. I assume that this has something to do with cache. So the simplest solution is to just clone the image and add it to the DOM (it is important that it be added to the DOM the get the with and height). Give the image a visibility value of hidden (do not use display none because it will not work). After you get the dimensions remove the clone.
Here is my code using jQuery:
This solution works in any case.
There's a lot of discussion in the accepted answer about a problem where the
onload
event doesn't fire if an image is loaded from the WebKit cache.In my case,
onload
fires for cached images, but the height and width are still 0. A simplesetTimeout
resolved the issue for me:I can't speak as to why the
onload
event is firing even when the image is loaded from the cache (improvement of jQuery 1.4/1.5?) — but if you are still experiencing this problem, maybe a combination of my answer and thevar src = img.src; img.src = ""; img.src = src;
technique will work.(Note that for my purposes, I'm not concerned about pre-defined dimensions, either in the image's attributes or CSS styles — but you might want to remove those, as per Xavi's answer. Or clone the image.)
How we get right real dimensions without a blink real image:
It works with <img class="toreaddimensions"...
Recently I needed to find width and height for setting default size of .dialog representing graph. Solution I use was :
For me this works in FF3, Opera 10, IE 8,7,6
P.S. You may be find some more solutions looking inside some plugins like LightBox or ColorBox