tags:

views:

27

answers:

1

Let me brief you the whole requirement first.

I have the following HTML code:

<div id="container">
  <ul>
    <li style="background-color:#CCC">One</li>
    <li style="background-color:#CCC">Two</li>
    <li style="background-color:#CCC">Three</li>
    <li style="background-color:#CCC">Four</li>
    <li style="background-color:#999">Five</li>
    <li style="background-color:#666">Six</li>
    <li style="background-color:#000; color:#FFF;">Seven</li>
    <li style="background-color:#000; color:#FFF;">Eight</li>
  </ul>
</div>    

CSS is like below:

<style type="text/css">
    #container { width:960px; overflow:hidden; margin:0 auto; border:1px dotted #CCC;}
    #container ul { padding:0; margin:0; white-space:nowrap; }
    #container li { list-style-type:none; display:inline-block; text-align:center; padding:0 15px; line-height:32px; margin:0; }
    * html #container li { display:inline; text-align:center; }  /* IE6 hack */
    * html #container { padding-bottom:17px;}  /* IE6 hack  */
    *:first-child+html #container li { display:inline; } /* IE7 hack */
    *:first-child+html #container { padding-bottom:17px; overflow-y:hidden; }  /* IE7 hack  */
</style>    

Now, we need to make the top navigation with LI - display:inline property. Condition is, in any scenario the menu will cover the 100% percent of the width. So each menu item will contain equal width. If there is One menu item then also it should cover 100% width.

I have achieved the same from the following code:

<script type="text/javascript">
    $(document).ready(function(){
        var w = 0;
        var tw = 960;
        var cal_width =0;
        w = $('li').size();
        cal_width = (tw/w)-30 + "px";
        $("ul > li").css({"width": cal_width});
    });
</script>    

Each LI will get equal width.

Now, what we need to do is like there are maximum of 7 items can appear in the top navigation at once. So, if the menu items exceeds the limit of 7 then a seperate UL will get generated on the run to wrap the items which are like 8th, 9th & so on.

By calculating the number of lines, we can run a for loop in jquery to generate UL tags on the run to wrap extra LI items which are greater then 7.

Can somebody help me out with this problem ?

+1  A: 

You could re-write the HTML of the initial DIV, might not be the best but would do the job, run this before you apply the classes.

var childCount = $("#container li").length;
if (childCount > 7) {
    var i=1;
    newHtml = "";
    $.each($("#container li"), function() { 
        if (i == 1) {
            newHtml +="<ul>";
        }
        newHtml += "<li>" + this.innerHTML + "</li>";
        if (i >= 7) {
            newHtml +="</ul>";
            i=1;
        } else {
            i++;
        }   
    });
    }
$("#container").html(newHtml)
});
dpmguise