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:
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;
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).
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With