Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to turn an unordered list into multiple columns

There doesn't seem to be an easy way in (well supported) css to do this. I'm looking for a javascript solution, preferably jQuery.

I have an unordered list like this:

<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>        
    ...etc
</ul>

I want each column to have a height for example four items and fill vertically rather than horizontally like a css float:

A     E
B     F
C
D
like image 292
Keyo Avatar asked Jul 12 '10 01:07

Keyo


People also ask

How do I display an unordered list in two columns?

This is the simplest way to do it. CSS only. add width to the ul element. add display:inline-block and width of the new column (should be less than half of the ul width).

Is there a way to break a list into columns?

If you want a preset number of columns, you can use column-count and column-gap, as mentioned above. However, if you want a single column with limited height that would break into more columns if needed, this can be achieved quite simply by changing display to flex.

How do you divide two columns in UL?

Add CSS. Use the columns property and specify “2” as a value. Also, add the -webkit- and -moz- prefixes.


1 Answers

You will want to use a combination of CSS and jQuery, but in theory it is very simple. Render a complete single list in HTML, then provide a wrapper via jQuery and split the list up as desired. The following function does just that. Be sure to use a more specific selector than just ul when actually using the script. An id would be ideal.

View demo here.

jQuery(function ($) {
  var size = 4,
      $ul  = $("ul"),
      $lis = $ul.children().filter(':gt(' + (size - 1) + ')'),
      loop = Math.ceil($lis.length / size),
      i    = 0;

  $ul.css('float', 'left').wrap("<div style='overflow: hidden'></div>");

  for (; i < loop; i = i + 1) {
    $ul = $("<ul />").css('float', 'left').append($lis.slice(i * size, (i * size) + size)).insertAfter($ul);
  }
});
like image 166
Doug Neiner Avatar answered Oct 23 '22 13:10

Doug Neiner