Evanss
Evanss

Reputation: 23593

Width of all contained elements + width of last element

I need a container div to be the combined width of all its images, plus the width of the last image. Ive got the width of the combined images with this:

$(window).load(function() {
    $('.pressimage').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
            totalImageWidth += $(this).width();
        });

        $(this).width(totalImageWidth);
    });
});

So how can I now add the width of the last image? Ive tried this but it doesn't work:

$(window).load(function() {
    $('.pressimage').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
            totalImageWidth += $(this).width();
        });


        $("img", this).last(function () {
            lastImageWidth = $(this).width();
        });

        $(this).width(totalImageWidth + lastImageWidth);
    });
});

Thanks

UPDATE. Sorry, I was working on the wrong code. Here's what I have which makes the div the width of all its images:

$(window).load(function() {

    var pub_accum_width = 0;

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
        pub_accum_width += $(this).width();
    });
    //alert(pub_accum_width);

        $('.view-public-collection .view-content').width(pub_accum_width);

}); 

And here is my modified code, but it hasn't made the div any wider:

$(window).load(function() {


    var pub_accum_width = 0;
    var pub_accum_last = 0;

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
            pub_accum_width += $(this).width();
    });


    $('.view-public-collection .pubimagecolor').find('img').last(function() {
        pub_last_width += $(this).width();
    });


    $('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);


});

Thanks

Upvotes: 1

Views: 1447

Answers (1)

aorcsik
aorcsik

Reputation: 15552

ANSWER FOR UPDATED QUESTION:

$(window).load(function() {
    var pub_accum_width = 0;
    var pub_last_width = 0; // not pub_accum_last

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
        pub_accum_width += $(this).width();
    });

    //                                                   ...last(function(...
    $('.view-public-collection .pubimagecolor').find('img').last().each(function() {
        pub_last_width += $(this).width();
    });

    $('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);
});

last() is a separate traversing function, you can not add a callback parameter to it. Select the last element with it, then use each(). Also you use different variable names.


You have to define the lastImageWidth variable outside of the last() callback each() callback after last(), to be able to use it outside again.

// ...
var totalImageWidth = 0;
var lastImageWidth = 0;
// ...

Upvotes: 3

Related Questions