jQuery Find number of items per row in floated li's

Deeptechtons picture Deeptechtons · Jul 18, 2012 · Viewed 15.8k times · Source

Is there a way to find number of items (li tag) inside a ul which has it's float: set to left. Assume i got loads of folders which are visually represented by li tags. Due to floating behavior as soon as the li does not fit in single row they will be pushed down giving it Rows and columns look.my questions is

Using jQuery ..etc Is there a way to determine the number of li for each row

Code

<ul>
 <li>A</li>
 <li>B</li>
 <li>C</li>
 <li>D</li>
 <li>E</li>
 <li>F</li>
 <li>G</li>
 <li>H</li>
 <li>I</li>
 <li>J</li>
</ul>

Style

ul,li{margin:0 0;padding:0 0;}
ul li{display:inline;float:left}

For my resolution li's upto F makes one row and the rest makes another like below. I would like a jquery way to get number of elements ( which is 6 in my case ) in row 1.

A B C D E F
G H I J

Context

I am adding keyboard events to navigate to each folder(li) using left,right,top,down. Left right is as simple as highlighting next and previous li's. Top and down keys need to go to next row and above row. Now you will get it :)

Answer

techfoobar picture techfoobar · Jul 18, 2012

We can do this by checking the number of LIs with their top (y-axis) positions matching that of their previous siblings.

Demo: http://jsfiddle.net/KgBpx/1/

Updated demo: http://jsfiddle.net/KgBpx/2/

Note: recalculation done on window resize as well to fully demonstrate the logic.

Code:

function calculateLIsInRow() {
    var lisInRow = 0;
    $('ul li').each(function() {
        if($(this).prev().length > 0) {
            if($(this).position().top != $(this).prev().position().top) return false;
            lisInRow++;
        }
        else {
            lisInRow++;   
        }
    });
    console.log('No: of lis in a row = ' + lisInRow);
}

calculateLIsInRow();

$(window).resize(calculateLIsInRow);

NOTE

The count of LIs will be same for all rows except maybe the last if the total number of LIs is not a multiple of lisInRow. The number of LIs in the last row can easily be found out by doing: $('ul li').length % lisInRow