24

I tried with something like this:

var Height = $(this).naturalHeight;

But it doesn't work. Is there any way to do that

greez

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
ValiL
  • 301
  • 1
  • 2
  • 7
  • 5
    `$(this)[0].naturalHeight;` but it's supported IE9+, see in some answers below for a wider browser support – Adriano Oct 13 '14 at 12:56

8 Answers8

54

I use the native javascript properties after applying jQuery and then stripping jQuery

.naturalWidth / .naturalHeight

On a jQuery object i use

var width = this.naturalWidth; 
var height = this.naturalHeight;

or

var width = $("selector").get(0).naturalWidth; 
var height = $("selector").get(0).naturalHeight;

if no jQuery object is selected.

With get(0) on a jQuery object you can access the associated DOM-element. On the native DOM element you can work with native javascript code (here access the nativ javascript attribute .naturalWidth)

Ruwen
  • 3,008
  • 1
  • 19
  • 16
  • "I use the native javascript attributes" should be revised to say "I use the native javascript properties after applying jQuery and then stripping jQuery". Consider what you're doing when you write `$(this)`. `this` is an `img` node which you're turning into a jQuery object. Then, `$(this)[0]` and `$(this).get(0)` gets you the original `img` node. There is no need for the jQuery middleman. Simply use `var width = this.naturalWidth;` and similarly for height. Your second example with `$("selector").get(0)` is fine if you prefer to use jQuery to locate a node for you. – MDMower Dec 21 '18 at 22:06
9

It looks to me like the accepted solution modifies the appearance of the object. Occasionally jQuery is a little too helpful and you have to tell it to get out of your way. If you want to use naturalWidth or naturalHeight then just use the one that already exists by converting the jQuery object into a native browser element reference.

var Height = document.getElementById($(this).attr("id")).naturalHeight;
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Geordie Korper
  • 155
  • 1
  • 2
  • 29
    Why not simply `this.naturalHeight`? – ThiefMaster Jun 16 '11 at 09:30
  • 7
    I agree with ThiefMaster. This answer is terrible code. `this.naturalHeight` is much faster, more compact and works on all objects, not only objects with an id. – jfriend00 Dec 20 '11 at 09:19
  • 5
    If you're already using jQuery then $(this)[0] is the HTMLElement instance, or $(this).get(0). Either one is better than repeating the getElementById call, since jQuery has done that for you. There are some (generally not cross-browser) attributes accessible only from the native HTMLElement class instead of the jquery-wrapped instance. – Luke H May 06 '12 at 17:25
  • 2
    $('selector')[0].naturalHeight – Boss Ninja Aug 09 '12 at 02:00
  • poor answer, see other comments & correct answers by `Boss Ninja`. Note: we write `$('selector')[0]` because we convert the jQuery element into a dom element (so we add this `[0]`), see http://stackoverflow.com/questions/2441535/convert-jquery-element-to-a-regular-dom-element – Adriano Oct 13 '14 at 12:59
  • Nothing assures that an element will have an `id`. – MrYellow May 27 '22 at 01:55
3

One way to get the dimensions of an image is to dynamically load a copy of the image using javascript and obtain it's dimensions:

// preload the image
var height, width = '';
var img = new Image();
var imgSrc = '/path/to/image.jpg';

$(img).load(function () {
    alert('height: ' + img.height);
    alert('width: ' + img.width);
    // garbage collect img
    delete img;
}).error(function () {
    // image couldnt be loaded
    alert('An error occurred and your image could not be loaded.  Please try again.');
}).attr({ src: imgSrc });
Corey Ballou
  • 42,389
  • 8
  • 62
  • 75
2

Here is an example of a jQuery function which works on older IE versions even for large images.

/*
 * NaturalWith calculation function. It has to be async, because sometimes(e.g. for IE) it needs to wait for already cached image to load.
 * @param onNaturalWidthDefined callback(img) to be notified when naturalWidth is determined.
 */
jQuery.fn.calculateNaturalWidth = function(onNaturalWidthDefined) {
    var img = this[0];
    var naturalWidth = img.naturalWidth;
    if (naturalWidth) {
        onNaturalWidthDefined(img);
    } else { //No naturalWidth attribute in IE<9 - calculate it manually.
        var newImg = new Image();
        newImg.src = img.src;
        //Wait for image to load
        if (newImg.complete) {
            img.naturalWidth = newImg.width;
            onNaturalWidthDefined(img);
        } else {
            $(newImg).load(function() {img.naturalWidth=newImg.width; onNaturalWidthDefined(img)});
        }
    }
};

Usage is simple:

$(img).calculateNaturalWidth(function(img) { alert(img.naturalWidth)});
ejboy
  • 4,081
  • 5
  • 30
  • 32
1

The best you can do is to hide an image without setting the width and height and use the image source for this image as your original image. Then calculate the dimension of this hidden image.

Or else you can calculate the physical dimension in server side and pass that to a hidden element in the page and fetch the size from that hidden element value.

rahul
  • 184,426
  • 49
  • 232
  • 263
1

Source From HERE

Here is a short jQuery (any version) plugin that adds two methods: naturalWidth() and naturalHeight(). It uses branching to determine if naturalWidth and naturalHeight are supported by the browser. If supported, the method just becomes a getter for the naturalWidth or naturalHeight property. If not supported, the method creates a new unstyled image element and returns that element's actual width and height.

  // adds .naturalWidth() and .naturalHeight() methods to jQuery
  // for retrieving a normalized naturalWidth and naturalHeight.
  (function($){
    var
    props = ['Width', 'Height'],
    prop;

    while (prop = props.pop()) {
    (function (natural, prop) {
      $.fn[natural] = (natural in new Image()) ? 
      function () {
      return this[0][natural];
      } : 
      function () {
      var 
      node = this[0],
      img,
      value;

      if (node.tagName.toLowerCase() === 'img') {
        img = new Image();
        img.src = node.src,
        value = img[prop];
      }
      return value;
      };
    }('natural' + prop, prop.toLowerCase()));
    }
  }(jQuery));

  // Example usage:
  var 
  nWidth = $('img#example').naturalWidth(),
  nHeight = $('img#example').naturalHeight();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Syed
  • 15,657
  • 13
  • 120
  • 154
0

Would just try

var width = $("img", this).css('width', 'auto').width();
var height= $("img", this).css('height', 'auto').height();

Is basically the calculation for naturalWidth and naturalHeight anyway

Tim
  • 2,466
  • 1
  • 21
  • 18
-15
$this.css('height', 'auto');
var height = $this.height();
ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
  • 8
    $(this)[0].naturalHeight will work in modern browsers, but from IE6-IE8 you should just create a new image element and get the width and height off of that. Setting the css to 'auto' is only going to work if that style has the highest specificity (which it will not necessarily have). Also the display of the image element and parent elements will affect it (display:none on any ancestor element will cause it to return 0). – Jack Oct 24 '11 at 01:52
  • @Jack +1 your plugin is much more robust than this answer, see also http://css-tricks.com/snippets/jquery/get-an-images-native-width/ – Adriano Oct 13 '14 at 12:55
  • Reading out CSS doesn't show the native image measures like HTML5' naturalWidth and naturalHeight do. – Bernhard Kraus Dec 12 '16 at 08:31