DavidF
DavidF

Reputation: 265

Jquery - Dynamically resize container DIV width container when another DIV is loaded inside

how can I change width with Jquery of a DIV container when another DIV is loaded inside (via PHP)?

This is my HTML code

<div id="container">
    <div class="item"> Content 1 </div>
</div>

Now, I have a to populate dinamically the "container" for each page. Another page may have this HTML code

<div id="container">
     <div class="item"> Content 1 </div>
     <div class="item"> Content 2 </div>
     <div class="item"> Content 3 </div>
</div>

"item" has float:left; I want all "items" in a row. How can I change the "container" width dynamically when a "item" is loaded inside?

I'm using a scrollbar Jquery plugin to scroll divs.

Please, help!

Upvotes: 0

Views: 1568

Answers (3)

Jeff B
Jeff B

Reputation: 30099

You could calculate the width of the children and apply the total to the container, like this:

var contentWidth = 0;

$('#container .item').each( function() {
    // outerWidth(true) includes margins
    contentWidth += $(this).outerWidth(true);
});

$('#container').width( contentWidth );

Demo: http://jsfiddle.net/jtbowden/SQASY/


Or, with some basic CSS, you could avoid doing it with JavaScript at all:

Demo: http://jsfiddle.net/jtbowden/YBKxn/1/

Upvotes: 1

MJC
MJC

Reputation: 3949

If the items have different width you can always do:

var totalWidth = 0;
$('#container').children('.item').each(function(){
   totalWidth += $(this).outerWidth();
});

$('#container').width(totalWidth);

Upvotes: 1

wezzy
wezzy

Reputation: 5935

do you need something like this ?

$(document).ready(function(){
    var youtWidth = 100;
    $('#container').width($('#container .item').length * yourWidth);
})

This count the elements inside the #container and set #container width to a multiple of the number of elements. In this example i keep 100px for each element.

Fabio

Upvotes: 1

Related Questions