popClingwrap
popClingwrap

Reputation: 4217

Find the width of an image that is part of an array generated by JQuery

I come from a Flash background (remember Flash :) but am pretty new to JS so be gentle.

I am building a carousel around a simple ul in which each li is an image.
I have an array of all the images in the list that I get using var list = $('#carousel li img');

If I examine list[0] in the console I see it is an HTMLImageElement and has both a width and clientWidth listed as 74 but if I try to get that width in my script (list[0].width, list[0].clientWidth, $(list[0]).width() etc) I just keep getting 0.

If I specify the width in the img tag then I get it ok but that just seems like extra typing unless there is a good argument for including it anyway.

Upvotes: 0

Views: 57

Answers (1)

alex
alex

Reputation: 490223

You need to load the image before you can acces its dimensions.

Check out an image element's load event. Note that it can be difficult to get working with already cached images.

You can get around that by always dealing with a new img element (new Image will create one).

Upvotes: 1

Related Questions