My goal was to make a list dynamically list itself into two columns, no matter the length of the list. I know this is possible by just floating the li
nodes, but I wanted to keep the li
nodes in the same vertical order. I would really like to hear from people who know more about JavaScript and jQuery than I do if this code looks good or if there is a better or more concise method for implementing this sort of thing.
Demo: http://jsfiddle.net/mkimitch/ZEL5x/
HTML:
<ul class="columned">
<li>Australia</li>
<li>Brazil</li>
<li>Canada</li>
<li>Chile</li>
<li>China</li>
<li>France</li>
<li>India</li>
<li>Italy</li>
<li>Malaysia</li>
<li>Norway</li>
<li>Russia</li>
<li>United Kingdom</li>
<li>United States</li>
</ul>
JavaScript:
var colLength = $('.columned li').length;
var colHeight = $('.columned').height();
var liHeight = $('.columned li').height();
if ($('.columned li').length % 2 != 0) {
var half = (Math.round(colHeight / 2)) + liHeight / 2;
} else {
var half = Math.round(colHeight / 2);
}
var firstrow = Math.ceil(colLength / 2);
var secondrow = firstrow + 1;
$('.columned li:nth-child(-n+' + firstrow + ')').addClass('column1');
$('.columned li:nth-child(n+' + secondrow + ')').addClass('column2');
$('.columned li:nth-child(' + secondrow + ')').css('margin-top', -half);