views:

139

answers:

3

Hello, I'm working on function, that takes a select from html and replaces it with multi-column ul - it's one list, but has float:left; on li children, so the number of columns is based on calculations (if ul width is 600 and li width is 200, i will obviously have 3 columns).

That's theory - the easy part.

Example: 5 items, 2 columns

Now, When I take data from select, I have this list:

 1
 2
 3
 4
 5

If I just push the array into ul, it will look like this on screen:

1   2
3   4
5

But for user/reader, it's easier and better, when you don't read Left->Bottom, but rather Bottom->Left, meaning that you're reading until bottom of column and then move to next column, rather than reading row, then next row.

So I need to transform list to columns:

1   4
2   5
3

so, in reality in ul will be this order:

1   4   2   5   3

And this needs to work with variable column number, because if we decide to add 10 items to list, it might look better with more columns.

Any help with needed operators/cycles and math involved?

Thank you

A: 

If you know how many columns there are, then you would make your <li> elements by skipping through the list n at a time. So for three columns, you pick items 0, 3, 6, ... and then come back and pick 1, 4, 7 and then 2, 5, 8.

Pointy
kind of what I was thinking as well. another might be to create multiple lists and put them side by side...same thought process just put first x in column 1, next x+ and so forth.
Mark Schultheiss
I tell how many there are... I was just kind of lost how to pick 0,3,6 and all that math. solved now :]
Adam Kiss
+2  A: 

I thought this was an interesting problem, so I wrote you a plugin for this. I tested it a little and it seems to work. Let me know if this is what you want!

http://jsbin.com/ocama/3/edit

http://jsbin.com/ocama/3

The algorithm is pretty simple, it pretty much just comes down to finding how many rows there are and grouping columns based on that number.

Alex Sexton
that's very nice :]
Adam Kiss
A: 

I made it :]

I did all the calulation. I also like Alex's solution, so I'll give him good answer and I add my solution here just for anyone looking for this kind of problem :)

var rows= 2; //editable number of rows

$('body').append('<ul id="fromselect"></ul>');
var o = $('select#tolist option');
var ul = $('ul#fromselect');

var total = o.size();
var onecol = Math.ceil(total / rows);
var index = 0; //index in o list

for (var j=1; j<=onecol;j++){
    for (var i=1;i<=rows;i++){
        if (!(i*j>total)){ //in last row, there might be less columns used
            index = (i-1)*onecol+j-1;
            ul.append('<li><a href="#">'+index +': '+
                      o.eq(index ).text()
                     +'</a></li>');
            //index is used more for debug, you can put
            //the index calculation in o.eq( * ) part
        }
    }
}
Adam Kiss