webmonkey237
webmonkey237

Reputation: 379

Auto percentage width based on children

I have a piece of jQuery code which automatically gives a div a percentage width based on the number of children which works well until you have more divs within the child div, how can I get this to ignore any divs inside the child ".eaService" and just give ".eaService" the calculated width.

Script

$(document).ready(function () {
var el = $('.servCon .eaService');
var len = el.children().length;
if (len > 0) {
    len = 100 / len;
    el.css("width", len + "%");
}
});

HTML

<div class="servCon">
        <div class="eaService">
            <div class="imgPanel"><img src="someimage.jpg" alt="" />
            </div>
            <div class="pad">
                <h3>Sub Heading</h3>
                <p>At Smith Jones we are committed to forming close partnerships with our clients, enabling us to understand... Find our more</p>
            </div>
        </div>
        <div class="eaService">
            <div class="imgPanel"><img src="someimage.jpg" alt="" />
            </div>
            <div class="pad">
                <h3>Sub Heading</h3>
                <p>At Smith Jones we are committed to forming close partnerships with our clients, enabling us to understand... Find our more</p>
            </div>
        </div>
</div>

Thanks

Upvotes: 1

Views: 45

Answers (2)

jered
jered

Reputation: 11581

Well, since you're specifically selecting the children of .eaService here, it's no wonder that you're counting up those elements.

What you're doing is $(".servCon .eaService").children(), which first selects all of your .eaService elements (in this case two) and then finds the children of those elements. The resulting selection includes both .imgPanel divs and both .pad divs.

What you probably mean to do is just find how many children .servCon has. So you want to do this:

var len = $(".servCon").children().length;

For maximum concision:

$(function(){
    $(".servCon").css("width", (100 / Math.max(1, $(".servCon").children().length)) + "%");
});

Upvotes: 0

The Process
The Process

Reputation: 5953

With var el = $('.servCon .eaService'); you are selecting both .eaService divs

so, when you call var len = el.children().length; you are getting the sum of their childrens, in this case it is 4, so then you are setting to .eaService width of 25%;

You should modify your code like here:

$(document).ready(function () {
var el = $('.servCon');
var childs=$('.eaService');
var len = el.children().length;
if (len > 0) {
    len = 100 / len;
    childs.css("width", len + "%");
}
});

Upvotes: 1

Related Questions