I am creating a jQuery plugin.
How do I get the real image width and height with Javascript in Safari?
The 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.
Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.
Using JavaScript In plain JavaScript, you can directly modify the CSS width and height property of the image.
Answer: Use the HTML5 naturalWidth and naturalHeight You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth and naturalHeight properties. These properties are supported in all major web browsers such as Chrome, Firefox, Safari, Opera, Internet Explorer 9 and above.
Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:
var img = $("img")[0]; // Get my img elem var pic_real_width, pic_real_height; $("<img/>") // Make in memory copy of image to avoid css issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; // Note: $(this).width() will not pic_real_height = this.height; // work for in memory images. });
To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.
You can also use the naturalHeight
and naturalWidth
HTML5 attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With