1

I'm looking for a bit of advice on this javascript (jQuery) issue (I'm not a frontend dev, so please bear with me ;-))

I have one large <ul> that I need to split in three separate <ul>s with an equal number of menuitems in each. So if I have five <li>s in my large <ul>, it will look like this:

Listitem 1           Listitem 3         Listitem5
ListItem 2           Listitem 4

etc.

Is there any way of doing this in javascript/jQuery? :-)

Thanks in advance.

bomortensen
  • 3,346
  • 10
  • 53
  • 74
  • Why not CSS and have a div: `div { -moz-column-count:3; /* Firefox */ -webkit-column-count:3; /* Safari and Chrome */ column-count:3; }` – mplungjan Jun 18 '13 at 08:11

3 Answers3

5

Css is always best for this however if you have to be backwards compatible or need it to be in separate lists for some other reason. I have knocked up a quick script for this. It could probably be a bit optimized as I just threw it together but does what you need.

I stuck it up on jsfiddle here http://jsfiddle.net/whAyt/8/ hope it helps

function breakList(numOfLists, list){
    var listLength = list.find("li").size();
    var numInRow = Math.ceil(listLength / numOfLists);
    for (var i=0;i<numOfLists;i++){
        var listItems = list.find("li").slice(0, numInRow);
        var newList = $('<ul/>').append(listItems);
        $("body").append(newList);
    }
}

breakList(3, $(".list")); 
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
  • Hi Dominic, thanks for a great answer :-) I tried tinkering around with your code and it works fine. Although, if there's an odd number of list items, it seems to miscalculate it. Check this updated jsfiddle where I have removed the last list item: http://jsfiddle.net/whAyt/6/ – bomortensen Jun 18 '13 at 09:03
  • Changed Math.round() to Math.ceil() and used "float: left;" instead of "display:inline-block"; :-) Works like a charm! – bomortensen Jun 18 '13 at 09:05
  • Good shout @bomortensen like I said this was just a quick nock up example I have updated with your suggestion – Dominic Green Jun 18 '13 at 14:56
0

How about CSS and a div?

div {
  -moz-column-count:3; /* Firefox */
  -webkit-column-count:3; /* Safari and Chrome */
  column-count:3;
}

More here

IE Alternative to Column-Count & Column-Gap

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

Still css only :

#theList { width: 100% }

#theList li {
    float: left;
    width: 33%;
}

fiddle

You would have to produce your <li> nodes in the correct order if you want to have them ordered by column.

LeGEC
  • 46,477
  • 5
  • 57
  • 104