Skip to content

Instantly share code, notes, and snippets.

@ataylorme
Created November 17, 2012 23:20
Show Gist options
  • Save ataylorme/4101322 to your computer and use it in GitHub Desktop.
Save ataylorme/4101322 to your computer and use it in GitHub Desktop.
Split <ul> with jQuery
$(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);
});
@ataylorme
Copy link
Author

jQuery function that accepts 2 parameters and splits un-ordered lists into multiples. Works well for creating creating columns if lists get too long. You can view the Fiddle here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment