PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

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();
    

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 ~