As the IE family doesn’t accept CSS3 column properties, I’m trying to split a list of li into 5 columns with javascript/jquery. In the process, I was told that looping an array backward is faster than looping it normally. I’ve tried it but it gives me a funny results. The last column is appearing as the 1st column, which I don’t want. I don’t know what’s wrong with the code. On top, the code reads slow in browser… Please give me some light.
JS/jQuery:
var JL = {}, JL.Module = {};
JL.Module.indexSort = function(){
var indexContainers = $('.index-section'),
indexControls = $('ul.index-navigation li'),
ieIndexContainers = $('.ie6, .ie7, .ie8, .ie9').find('.index-section'),
ulWrap = '<ul class="new-col" />',
colCount = 5,
subLi;
indexContainers.hide().filter(':first').show();
indexControls.filter(':first').addClass('selected');
//IE family don't accept css columns properties, so have to use JS
ieIndexContainers.each(function () {
var thisElem = $(this),
indexUl = thisElem.find('ul'),
indexLi = thisElem.find('li'),
indexLiLen = indexLi.length,
liPerCol = Math.ceil(indexLiLen / colCount),
lastColCount = indexLiLen % liPerCol,
sliceStart = indexLiLen - lastColCount,
sliceEnd = indexLiLen,
subLi,
i;
ieIndexContainers.find('ul').addClass('new-col');
setTimeout(function(){
sliceEnd = 0;
sliceStart = -1;
// Looping the array backwards
for(i = colCount - 1; i > 0; i--){
sliceEnd = sliceStart;
sliceStart = (sliceEnd - liPerCol >= 0) ? sliceEnd - liPerCol : 0;
subLi = indexLi.slice(sliceStart, sliceEnd);
indexUl.after($(ulWrap).append(subLi));
}
ieIndexContainers.find('.new-col').show();
}, 0);
});
}
HTML:
<div id="s" class="index-section">
<h2>s</h2>
<ul>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Aorem</a></li>
<li><a href="#">Apsum</a></li>
<li><a href="#">Aonor</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asdijnd oasd</a></li>
<li><a href="#">Awrom</a></li>
<li><a href="#">Aoidn iojd</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asddewdwe</a></li>
<li><a href="#">Apsum</a></li>
<li><a href="#">Aonor</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asdijnd oasd</a></li>
<li><a href="#">Awrom</a></li>
<li><a href="#">Aoidn iojd</a></li>
<li><a href="#">Lorem ipsum</a></li>
<li><a href="#">Asddewdwe</a></li>
</ul>
</div>
Just loop it forward. The being slower relates to not caching the array’s length. However, you do cache the upper bound of the for-loop in
colCount. Don’t worry about performance, just do the loop the right way around. Let it count forward.