Seedorf
Seedorf

Reputation: 675

How to add the widths of all the images in a div with JQuery

I was looking for a way to change the width of a div to the sum of all the widths of the images within that div.

In other words, I wanted #page-content to have a width that is equal to the width of all the images inside it. This is because i would like the page-content div to be wider than the browser window, so that the user can scroll from left to right.

the code I had was as follows:

    <div id="page-content">
    <div id="gallery">
        <div>
            <a href="#" class="shutterset">
                <img src="images/pic1.jpg"/>
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic2.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic3.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic4.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic5.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic6.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic7.jpg" />
            </a>
            <a href="#" class="shutterset" >
                <img src="images/pic8.jpg" />
            </a>
        </div>
        <div class="clear"> </div>
        <p>hi</p>
    </div>
</div>

And the jQuery I tried out was:

        $(document).ready(function() {
        $("p").html($("#gallery img:first").width());
    });

I'd done this to test to see if the width was being calculated, but it doesnt seems to be. The result is always 0, as opposed to the width of the image.

Would appreciate any help

Seedorf

Upvotes: 1

Views: 1596

Answers (2)

Fosco
Fosco

Reputation: 38516

I suggest adding a class to the images as you have the links, i.e. <img class="shutterimg" and trying this in a $(window).load function to be sure they have loaded:

var totalwidth = 0;
$('img.shutterimg').each(function() {
    totalwidth += $(this).width();
});
$('#gallery').width(totalwidth);

Upvotes: 6

lonesomeday
lonesomeday

Reputation: 237845

Image widths are not calculated until the image is downloaded, unless the width attribute is specified. Your handler executes on $(document).ready() -- this is when the whole DOM has loaded but will almost certainly be before the images have loaded.

Wait for the $(window).load() event instead: this is triggered when all the content (images, stylesheets and scripts) has loaded.

$(window).load(function() {
    $("p").html($("#gallery img:first").width());
});

Upvotes: 3

Related Questions