0

I have the following code

img = document.getElementById('image'); // which is an <img> element

if (img.width > 0) {
    // I get here in Chrome, width is correct
} else {
    // I get here in Safari, width is 0
}

Why is the width property 0 in Safari and how can I solve this?

Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • Wait for the image to be loaded before accessing its dimensions—the image might not be loaded get when you probe for its width. – Terry Aug 09 '15 at 14:39
  • @Terry Thanks, this actually solved my problem. The images src attribute is actually dynamically set, so in Safari the code above was executed too quickly, before the image was even loaded. I guess Chrome is faster in generating images or something. However, since your solution was the one that work, if you write up an answer regarding this I'll mark it as "Answered". FYI, I used $('#image').load(function() { } to do what you suggested. – Weblurk Aug 09 '15 at 14:55

3 Answers3

1

Although it should really matter, try using .clientWidth instead of .width

This answer explains that

In the case of an IMG element, this will get the actual dimensions of the visible image.

HTML

<img id="image" width="0" height="100" src="http://placehold.it/100x100"/>

JavaScript

var img = document.getElementById('image'); // which is an <img> element

if (img.clientWidth > 0) {
    // I get here in Chrome, width is correct
    console.log('Do something if greater than 0')
} 
else {
    // I get here in Safari, width is 0
    console.log('Do something else if not greater than 0')
}

Here's a quick Codepen link to show it working in both browsers

Community
  • 1
  • 1
Alan
  • 362
  • 3
  • 9
  • 18
0

Have you tried to read the "offsetWidth" object.

img = document.getElementById('image');
img.offsetWidth // here you go
Alex Pereira
  • 916
  • 1
  • 9
  • 17
0

It is likely that Safari does not have access to the image's dimensions, and therefore is unable to compute its width and height when you probe for it.

You should wait for the image to load, which fires an event handler for which you can fetch the image dimensions from within.

Terry
  • 63,248
  • 15
  • 96
  • 118