Skip to content

Instantly share code, notes, and snippets.

@johan
Created March 26, 2012 21:40
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save johan/2209957 to your computer and use it in GitHub Desktop.
Save johan/2209957 to your computer and use it in GitHub Desktop.
jQuery.naturalWidth / jQuery.naturalHeight plugin for (already-loaded) images
// jQuery.naturalWidth / jQuery.naturalHeight plugin for (already-loaded) images
// Triple-licensed: Public Domain, MIT and WTFPL license - share and enjoy!
(function($) {
function img(url) {
var i = new Image;
i.src = url;
return i;
}
if ('naturalWidth' in (new Image)) {
$.fn.naturalWidth = function() { return this[0].naturalWidth; };
$.fn.naturalHeight = function() { return this[0].naturalHeight; };
return;
}
$.fn.naturalWidth = function() { return img(this.src).width; };
$.fn.naturalHeight = function() { return img(this.src).height; };
})(jQuery);
@paulkoegel
Copy link

can't i just use $('#my-image').prop('naturalWidth')?

@johan
Copy link
Author

johan commented Jul 30, 2012

If you only care for supporting webkit and other modern browsers: certainly! No portability shim needed for that.

@ph0b0s
Copy link

ph0b0s commented Sep 12, 2012

IE (<9) doesn't have width/height of image until load event finishes (img(this.src).complete===true).
did you try this in IE7-8?

@WaYdotNET
Copy link

Many thanks !!!

@kihlstrom
Copy link

Hi!
I made a small change in order to make this work as intended in IE8 as well.
See --> https://gist.github.com/kihlstrom/8316718/revisions

Cheers! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment