Sheixt
Sheixt

Reputation: 2626

Dynamically percentage width assignment with jQuery

I've got a simple piece of jQuery running to assign a width to my list items:

    $(subMenu).each( function() {
        var noLi        = $(this).children('li').length,
            itemSize    = (10/noLi)*10;
        $(this).children('li').each( function() {
            $(this).css('width', itemSize +'%');
        });
    });

I know there are always less than 10 list-items in this case so I am generating the percentage width by the simple itemSize calculation. However if more items were added, the whole thing would fail & the layout would not be as intended.

I also believe this may not be the most efficient way to achieve this in the first place, but am unsure of a better way. Can someone point me in the right direction?

Upvotes: 2

Views: 1281

Answers (2)

Steve
Steve

Reputation: 31652

First, you don't need to make any assumptions about how many items you're going to have. If you just want to divide the 100% width into x number of items, you can simply use 100 / x.

Also, there is no need for the nested .each you have. jQuery does that automatically.

$(subMenu).each(function() {
    var items = $(this).children('li');
    var itemSize = 100 / items.length;
    items.css('width', itemSize +'%');
});

Upvotes: 1

Martijn
Martijn

Reputation: 16123

You mean itemSize gets to big? If so, you can do this:

itemSize = Math.min(100, (10/noLi)*10); // Get smallest value of the two. 100 is the max now

About adding sizes, you can replace the code to this:

 $(this).children('li').css('width', itemSize +'%'); // no need for each

Combined would be:

$(subMenu).each( function() {
    var $AllLi  = $(this).children('li'); // Save'm all for later access
    var noLi    = $AllLi.length; // we saved all selected li´s so we dont need to reselect
    itemSize    = Math.min(100, (10/noLi)*10);
    $AllLi.css('width', itemSize +'%'); // no need for each
});

Another way might be better, using css:

<style>
    ul{
        width: 100%; 
        display: table-row;
    }
    li{
        display: table-cell;
    }
    li:gt(10){
        display: none;
    }
</style>
<ul>
    <li>li part</li>
    <li>li part</li>
    <li>li part</li>
    <li>li part</li>
</ul>

Upvotes: 1

Related Questions