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

Share this article

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

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form