Razvan Cuceu
Razvan Cuceu

Reputation: 577

jQuery width of element added in loop

I want to make all the images inside a wrapper div to be next to each other. I have set the height of the images to 100% and the width to auto, position absolute, top: 0. I need to make a jQuery code that calculates the width of the image and sets the left position of second image to width of first image. All the images will have the same width. enter image description here

I have this not-working, incomplete code, that I have fight with

$('.page-wrap .portfolio-item').each(function(i){
    var width = $('.portfolio-item').width();
        $(this)
        .animate({left: width});
    });

FIDDLE: http://jsfiddle.net/en9ub923/

Upvotes: 0

Views: 674

Answers (2)

Josh Beam
Josh Beam

Reputation: 19772

Update

If you need to be able to scroll through the contents, you can do something like this (see the updated jsfiddle):

Output:

flexbox-with-overflow

HTML:

<div class="overflow-container">
    <main>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </main>
</div>

SCSS:

main {
    background: lightblue;
    display: flex;
    flex-wrap: nowrap;
    height: 60px;
    justify-content: space-between;
    padding: 2px;
    width: 100vw;

    div {
        background: lightgreen;
        flex-grow: 1;
        height: 60px;

        &:not(:last-child) {
            margin-right: 2px;
        }
    }
}

.overflow-container {
    height: 64px;
    width: 300px;
    overflow-x: scroll;
}

Old answer

If you're willing to not support some older browsers (well, actually just use modernizr and you won't have to worry about that), you could try CSS flex-box (see the jsfiddle):

SCSS:

main {
    background: lightblue;
    display: flex;
    flex-wrap: nowrap; // keep the elements on the same line
    height: 60px;
    justify-content: space-between;
    padding: 2px;
    width: 100%;
}

div {
    background: lightgreen;
    flex-grow: 1; // every element will take up equal space
    height: 60px;

    &:not(:last-child) {
        margin-right: 2px;
    }
}

Output:

flexbox

The width of the children fits to the container (the children could be anything, imgs included.)

Upvotes: 1

Daniel Cardoso
Daniel Cardoso

Reputation: 478

Fiddle with css only solution: http://jsfiddle.net/se3bjch4/1/

Why not use for your img css:

display: inline-block;

or:

float:left;

!?

Or change your code to this to go with your approach:

var all_images_width = 0;
$('.page-wrap .portfolio-item').each(function(i, val){
    var width = $('.portfolio-item').width();
    $(this).animate({left: all_images_width});
    all_images_width += width;
});

Upvotes: 3

Related Questions