abiku
abiku

Reputation: 2246

jquery img width() gives 0

strange problem do you know why this code:

var img = new Image();
img.src = 'images/img1.jpg';

$(img).on('load', function() {
   alert($(this).width());

});

gives 0 in Firefox, Chrome but gives correct value in IE9? How to get the proper value in all browsers? using jQuery 1.8.2

Upvotes: 2

Views: 1606

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173532

The way that jQuery determines dimensions of objects is by inspecting the style attribute (afaik); since the image never gets added to the DOM, it wouldn't know that.

Having said that, I don't see a particular reason why you need jQuery here:

var img = new Image();
img.onload = function() {
    alert(this.width);
}
img.src = 'http://example.org/path/to/image.jpg';

To set the dimensions using jQuery you could use this:

$(this)
    .width(this.width)
    .height(this.height);

Not sure why you need it though, because at rendering time the browser will already know how big the image is, unlike adding an <img /> to the DOM

Btw, the order of these statements is important; you should register the load handler before setting the .src property, otherwise you might miss the load event if an image has been cached by the browser.

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

Until you append the image in to dom .width() returns 0

var img = new Image();
img.src = 'http://jsfiddle.net/img/logo.png';
$(img).on('load', function() {
    console.log(this.width); // 160
    console.log($(this).context.width); // 160
    console.log($(this).width()); // 0
    $('body').append($(this));
    console.log($(this).width()); // 160
});

Check this.

Upvotes: 3

pna
pna

Reputation: 5761

As per jQuery documentation http://api.jquery.com/load-event/

Caveats of the load event when used with images: A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

1.It doesn't work consistently nor reliably cross-browser 2. It doesn't fire correctly in WebKit if the image src is set to the same src as before 3. It doesn't correctly bubble up the DOM tree 4. Can cease to fire for images that already live in the browser's cache

If you look at the comments down the documentation, many people have the same problem because the load event is not fired in webkit, usually when the src is set as the same before... maybe you want to set a placeholder image and then change the src attribute.

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

jsBin demo

var img = new Image();
img.src = 'images/img1.jpg';

$(img).on('load', function() {
   alert(this.width);
});

Or with pure JS:

var img = new Image();
img.src = 'images/img1.jpg'; 

img.onload = function() {
   alert(this.width);
};

Upvotes: 4

Related Questions