split UL

by ataylor

HTML

<ul class="split-me">
<li>AA</li>
<li>BB</li>
<li>CC</li>
<li>DD</li>
<li>EE</li>
<li>FF</li>
<li>GG</li>
<li>HH</li>
<li>II</li>
<li>JJ</li>
<li>KK</li>
<li>LL</li>
<li>MM</li>
<li>NN</li>
<li>OO</li>
<li>PP</li>
<li>QQ</li>
<li>RR</li>
<li>SS</li>
<li>TT</li>
<li>UU</li>
<li>VV</li>
<li>WW</li>
<li>XX</li>
<li>YY</li>
<li>ZZ</li>
</ul>

CSS

ul {border: 1px solid red;}

JavaScript

$(document).ready(function() {

    function splitSubmenu(ulSelector,maxNumItems) {
        $(ulSelector).each(function () {
    
            // get all child li tags
            var list$ = $(this).children("li");
            var num, nextAfter$, after$ = $(this);
    
            // as long as the current list is too long, loop
            while (list$.length > maxNumItems) {
                // decide how many to remove this iteration
                num = Math.min(maxNumItems, list$.length - maxNumItems);
                // create new UL tag, append num items to it 
                // and insert it into the DOM
                nextAfter$ = $('<ul class="' + ulSelector + '">')
                    .append(list$.slice(maxNumItems, maxNumItems + num))
                    .insertAfter(after$);
                // update insertion point for next loop iteration
                after$ = nextAfter$;
                // remove the items we just took out from the current jQuery object
                list$ = list$.filter(function(index) {
                    return(index < maxNumItems || index >= 2 * maxNumItems);
                });
            }
        });
    }
    
    splitSubmenu('.split-me',4);
        
});