JavaScript
Article
By Sam Deering

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

By Sam Deering

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.

--ADVERTISEMENT--

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

    Recommended
    Sponsors
    The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
    Login or Create Account to Comment
    Login Create Account