The Problem
I was working on a project that required us to include an entire list of all our clients, by using the WordPress Links feature. It was easy enough to generate a whole list by using the wp_list_bookmarks() but that would only generate a long list like so:
- Item 1
- Item 2
- Item 3
- Item 4
- Item 5
- Item 6
- Item 7
- Item 8
- Item 9
When what we really wanted was to create a dynamic list into three even columns across the page, like so:
- Item 1
- Item 2
- Item 3
- Item 4
- Item 5
- Item 6
- Item 7
- Item 8
- Item 9
I had found a way to achieve this using CSS which was my preferred method, but the list could only be ordered alphabetically left to right, not top to bottom like in the example above.
So I resulted to using a little bit of jQuery to get the job done.
The Solutions
HTML Markup:
</pre> <ul class="list-items"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> <li>Item 7</li> <li>Item 8</li> <li>Item 9</li> </ul> <pre>
The example is a static list, although when I needed to do this I used the WordPress call wp_list_bookmarks and specified the ul class name ‘list-items’.
jQuery:
var postsArr = new Array(), $postsList = $('ul.list-items'); //Create an array containing all list items $postsList.find('li').each(function(){ postsArr.push($(this).html()); }) //First column, split the whole list by a third. var firstList = postsArr.splice(0, Math.round(postsArr.length / 3)), //Secound column, take one half of the remaining list items. secondList = postsArr.splice(0, Math.round(postsArr.length / 2)), //Third column, put the remaining items into an array. thirdList = postsArr, ListHTML = ''; function createHTML(list){ ListHTML = ''; for (var i = 0; i < list.length; i++) { ListHTML += '<li>' + list[i] + '</li>' }; } //Generate HTML for first list createHTML(firstList); $postsList.html(ListHTML); //Generate HTML for third list createHTML(thirdList); //Create new list after original one $postsList.after('<ul class="list-items"></ul>').next().html(ListHTML); //Generate HTML for second list createHTML(secondList); //Create new list after original one $postsList.after('<ul class="list-items"></ul>').next().html(ListHTML);
Here is the end result in Codepen:
Check out this Pen!
If anyone out there know how to achieve the same results by only using CSS let us know!
The post Split a Dynamic List into Columns appeared first on Patrick Skotniczny.