JavaScript - - By Sam Deering

jQuery Convert a List to Columns – $.list2Columns()

convert-to-columns

I thought I would share with you a jQuery function I wrote to convert a list (UL or OL) into columns. Could be quite useful if your list comes in and reads from top to bottom it will separate the list items into vertically spaced columns.

The Code

$.fn.extend(
{
    list2Columns: function(numCols)
    {
        var listItems = $(this).html().match(/(
  • .+)/igm); /* get the list data */ var listHeader = $(this).html().match(/(
      /igm); var numListItems = listItems.length; var numItemsPerCol = Math.round(numListItems / numCols); /* divide by the number of columns requires */ var currentColNum = 1, currentItemNumber = 1, returnHtml = '', i = 0; $(this).empty(); /*clean previous content */ /* append the columns */ for (i=1;i
    '); } /* append the items to the columns */ $.each(listItems, function (i, v) { if (currentItemNumber Usage [js] $('#countries').list2Columns(4);
  • Demo

    • Afghanistan
    • Albania
    • Algeria
    • Australia
    • Austria
    • Bahamas
    • Bahrain
    • Bangladesh
    • Barbados
    • Belarus
    • Canada
    • Comoros
    • Congo
    • Cook Islands
    • Costa Rica

    Sponsors