Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get grid row/col position given an item index

If I have a container with a width of 1000px, filled with items all of which are 200px in width. How can I calculate that tiles row/column position?

To explain in more detail:

enter image description here

The only variables I will know is the width of the container (1200px in the above example) , the width of an item (200px above) and the items index (starting at 1).

Given only the above information, how can I calculate the row and column of a cell by inputting its index using javascript.

e.g. Given a maximum items per row value of 6 (which can easily be calculated from the item width and container width), I need to be able to calculate that item number 7 is at row 2, column 1.

The container and item width's might not always be divisible exactly so the equation will have to account for any extra whitespace requires at the end of each row and naturally wrap the items onto the next row as they would in an html float layout.

Thanks in advance

EDIT:

I have managed to get the row quite accurately by doing the following:

var itemsperrow = Math.floor(containerwidth/ itemwidth);
var column = Math.ceil(itemindex / itemsperrow )

This is with the items index starting at 1 and not 0;

like image 626
gordyr Avatar asked Mar 19 '13 21:03

gordyr


2 Answers

  1. Find how many elements fit in one row by taking the floor of (row width)/(element width).
  2. Divide the index number given by the elements per row (which you just figured out). That will give you the row position.
  3. Next find the column position by taking the remainder portion from step 1 (you can use modulus). Multiply the remainder by the number of elements per row. That will be which column it is in.

example: 3 elements per row, 4th element: floor(4/3) = 1 (row 1) remainder = (4%3)=1 (column position)

Be careful of what index you are starting with (whether it's 0 or 1). This example starts at 1. If you want to start at 0 shift it over by subtracting 1 (the index number).

like image 166
user829323 Avatar answered Oct 20 '22 17:10

user829323


Something like this?

var cells = document.querySelectorAll('.container').children(),
    container_width = 1200,
    cell_width = 200,
    total_cols = container_width/cell_width,

    calculateCoords = function (index) {
        return coords {
            col: index%total_cols,
            row: Math.ceil(index/total_cols)
        };
    };

//EXAMPLE USAGE FOR CELL INDEX = 3;
var index_3_coords = calculateCoords(3);
console.log(index_3_coords); //{ col: 3, row: 1 }
like image 33
João Paulo Macedo Avatar answered Oct 20 '22 18:10

João Paulo Macedo