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.
You can programmatically get the image and check the dimensions using Javascript without having to mess with the DOM at all.
This works for both cached and dynamically loaded images.
To use this script:
Demo: http://jsfiddle.net/9543z/2/
Stumbled upon this thread trying to find an answer for my own question. I was trying to get an image's width/height in a function AFTER the loader, and kept coming up with 0. I feel like this might be what you're looking for, though, as it works for me:
You can use the naturalWidth and naturalHeight properties of the HTML image element. (Here's more info).
You would use it like this:
It seems like this works in all browsers except on IE from version 8 and below.
For functions where you do not want to alter the original placement or image.
As stated before, Xavi answer won't work if images are in the cache. The issue responds to webkit not firing the load event on cached images, so if the width/height attrs are no explicitly set in the img tag, the only reliable way to get the images is to wait for the
window.load
event to be fired.The
window.load
event will fire always, so it's safe to access the width/height of and img after that without any trick.If you need to get the size of dynamically loaded images that might get cached (previously loaded), you can use Xavi method plus a query string to trigger a cache refresh. The downside is that it will cause another request to the server, for an img that is already cached and should be already available. Stupid Webkit.
ps: if you have a QueryString in the
img.src
already, you will have to parse it and add the extra param to clear the cache.