Grow your CSS skills. Land your dream job.

Last updated on:

Get an Images Native Width

If you select and image with jQuery and then use .width(), you'll get the images current width, even if it's been scaled (e.g. max-width: 100%;). You can access the images native width (even if it doesn't have any attributes which declare it) like this:

// Get on screen image
var screenImage = $("#image");

// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");

// Get accurate measurements from that.
var imageWidth = theImage.width;
var imageHeight = theImage.height;

Comments

  1. Hans Kuijpers
    Permalink to comment#

    Hi Chris,

    When I look at the code I don’t understand two things:
    1. Why don’t you use the first created var screenImage further in the script?
    2. Where does mainScreenshot come from?

    (I’m trying to learn jQuery a bit)

  2. Very subtle Chris. This is a great usage of native objects of JavaScript. I think it can simply become a jQuery plugin, like:

    
    $('#image-id').realWidth();
    
  3. Richard
    Permalink to comment#

    I discovered that Chrome/FF had an extra attribute for images when working on a custom carousel. Here is a little function I wrote that uses the properties if they exist, and sets them if they don’t. One big assumption (as with the original example) is that the sizes are available immediately. Technically having a separate function on browsers without ‘natural(width|height)’ that fills in the value before you need it would be ‘safer’.

    function imgRealSize(img) {
    	var $img = $(img);
    	if ($img.prop('naturalWidth') == undefined) {
    		var $tmpImg = $('<img/>').attr('src', $img.attr('src'));
    		$img.prop('naturalWidth', $tmpImg[0].width);
    		$img.prop('naturalHeight', $tmpImg[0].height);
    	}
    	return { 'width': $img.prop('naturalWidth'), 'height': $img.prop('naturalHeight') }
    }
    
  4. Kwadwo
    Permalink to comment#

    Hi Chris,
    Thumbs up for your help. I find the ‘RevealingPhotoSlider’ very interesting, however, it is not compatible with Chrome. On clicking ‘MORE INFO’, in Chrome, the image does not show up but rather shrinks. Also in IE8. Am just creating my website so don’t have the ‘live’ link, hence could not put a web address, sorry, and I hope to hear back from you soon.

    Thank you.

  5. Permalink to comment#

    I found this would only work in Chrome within $(window).load — $(document).ready seems to fire too soon.

  6. clemi
    Permalink to comment#

    @Graham: only the image has to be loaded before calculating, you can use $(‘#image’).load
    works in all browsers I tested so far, mobile as well

    thanks a lot, chris

  7. Ravi
    Permalink to comment#

    returning native height and width as zero.

  8. Liam Monticelli
    Permalink to comment#

    There are bound to be cases where we need the dimensions of an image that hasn’t loaded yet, e.g. an image in a hidden layer. Here’s the workaround I’ve come up with for such situations:

      $(imgs).each(function(){
    
        // Create new offscreen image to test
        var theImage = new Image();
        theImage.src = $(this).attr("src");
        // Add a reference to the original.
        $(theImage).data("original",this);
    
        // Get accurate measurements from that.
        $(theImage).load(function(){
          var imageWidth = this.width;
          var imageHeight = this.height;
          $($($(this).data("original")).css("width",imageWidth+"px");
        });
      });
    

    where imgs is a collection of <img> elements.

  9. Adam
    Permalink to comment#

    There is an issue on getting the native width on firefox and IE

    is there a way to get that issue fixed?

  10. Tharaka
    Permalink to comment#

    If image is cached (for eg. using output cached in IIS 7.5) above method didn’t work in iPhone 5+

  11. Jens
    Permalink to comment#

    Good idea, but don’t work…follwoing script do the trick for me.

    jQuery.fn.realSize = function() {

    var i = $(this.filter( 'img')).first();
    
    if( i) {
    
        if( !i.data( 'realSize')) {
    
            var _w = i.width(),
                _h = i.height();
    
            i.width( 'auto').height( 'auto');
    
            i.data( 'realSize', { width: i.width(),
                                  height: i.height()});
    
            i.width( _w).height( _h);
    
    
        }
    
        return i.data( 'realSize');
    
    }
    
    return undefined;
    

    };

    jQuery.fn.realWidth = function( options) {

    var rs = this.realSize();
    
    return rs ? rs.width : undefined;
    

    };

    jQuery.fn.realHeight = function( options) {

    var rs = this.realSize();
    
    return rs ? rs.height : undefined;
    

    };

    $( ‘img’).realSize(); // Object {width: 960, height: 720}

  12. angel
    Permalink to comment#

    Jens your solution work fine for me ;)
    I addon this on jQuery JavaScript Library v2.1.0

    Perfect thk man

  13. jamie
    Permalink to comment#

    Just what I needed today! Thanks – even a couple of years on still useful :)

  14. Ian
    Permalink to comment#

    Chris / All
    Is there any way to do something like this?

    img width:100%;
    img max-width:NATURAL;

    So I don’t want an image to become pixelated but if it’s big enough go to 100%.

    • slomo
      Permalink to comment#

      Ian, that should be simple as

      img {
          width: auto;
          max-width: 100%;
      }
      
  15. jens
    Permalink to comment#

    Hey Chris,

    i think following do the trick for you.

    $( ‘img’).css( ‘max-width’: $( ‘img’).realSize().width);

  16. Ian
    Permalink to comment#

    jQuery is fine but I was looking for a CSS only answer. Seems odd that you can’t specify the natural image width unless you omit the CSS width altogether.

  17. Kenyon
    Permalink to comment#

    This is works great for me on local images but when using images on a CDN, it seems to only pick up the size on first load only, if you call the function on window.resize the function returns 0.

    Here’s a jsFiddle: http://jsfiddle.net/WKzJ4/2/

    Any solutions to this?

    • Brian
      Permalink to comment#

      Kenyon,

      Did you ever find a solution for finding the natural size of an image on a CDN? Thanks for any help.

  18. Jens
    Permalink to comment#

    Hey Kenyon,

    i’m not sure what do you like to do. The sense of the code was determine the original size of an image.

    Btw. : get original size of an image with «new Image()» works not fine.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".