4

I have the following jQuery and wanted to test if naturalWidth is supported:

function special(image) {
    if (typeof this.naturalWidth != 'undefined') {
        //do something
    }
}

But this doesn't seem to work ? Any ideas ?

Adriano
  • 19,463
  • 19
  • 103
  • 140
Tom
  • 43
  • 3
  • related: http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-a-property-in-javascript (what a mess!!) – Adriano Oct 14 '14 at 09:48

2 Answers2

2

Try this

function special(image) {
    if (image && image.naturalWidth) {
        //do something
    }
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1

Why not just include a naturalWidth / naturalHeight polyfill? https://gist.github.com/2209957

Given that, you can write code like alert($(img).naturalWidth()) where you'd otherwise have used alert(img.naturalWidth) and it should now work in all browsers, whether they support it natively or not.

ecmanaut
  • 5,030
  • 2
  • 44
  • 66
  • +1, `naturalWidth` & `naturalHeight` are "only" IE9+ supported so I'd include a polyfill. You may want checkout this other polyfill https://gist.github.com/kroleg/5388163 , note that I have not tested it yet. And this one as well https://github.com/desandro/imagesloaded – Adriano Oct 13 '14 at 14:00