Code Snippet

Home » Code Snippets » jQuery » Get an Images Native Width

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;

Subscribe to The Thread

  1. Hans Kuijpers

    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

    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

    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. I browser this website about 15 days ago. And it’s now it’s my most favorite website. I just checked this tutorial and I really don’t understand. If the tutorial is little then it would be easier to people like me.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~