ak85
ak85

Reputation: 4264

Jquery get the width of each image

I am trying to get the width of each image in my class img-wrap and apply that width to the img-caption class for each item. The code I have below only works for the first item.

    <div class="img-wrap">
        <img src="http://lorempixel.com/300/100" />
        <div class="img-caption">aa</div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/400/100" />
        <div class="img-caption"></div>
    </div>
    <div class="img-wrap">
        <img src="http://lorempixel.com/500/100" />
        <div class="img-caption">cc</div>
    </div>

    <script>
    var imgwidth = 0;
    $('.img-wrap').each(function (index, value) {
        imgwidth = $('.img-wrap img').width();
        if ($('.img-caption').text() === '') {} else {
            $(this).css("background-color", "#000");
            $(this).css("color", "#fff");
            $(this).css("width", imgwidth);
        }
    });
    </script>

Then that width is applying to all classes. What am I missing here to get the width to apply to each img-caption. Eg in my example instead of them all being 300px wide as this is the width of the first image they should be 300,400,500. I have the else like that as I am probably going to add something to the if later but not relevant to the question.

Upvotes: 0

Views: 788

Answers (2)

Stuart Kershaw
Stuart Kershaw

Reputation: 17671

Try:

imgwidth = $(this).children('img').width();

Here's the working example: http://jsfiddle.net/EmE39/

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388326

You need to wait for the images to be loaded before finding the width of it

$('.img-wrap img').load(function () {
    var $this = $(this);
    $this.parent().css({
        "background-color": "#000",
        "color": "#fff",
        "width": $this.width()
    });
});

Upvotes: 2

Related Questions