How can I get the grid / column position based on the index of an element

If I have a container with a width of 1000 pixels filled with elements, all of which are 200 pixels wide. How can I calculate the tile / column position?

To explain in more detail:

enter image description here

The only variables that I will know are the width of the container (1200 pixels in the above example), the width of the element (200 pixels above) and the index of objects (starting from 1).

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

eg. Given the maximum values ​​for line in line 6 (which can be easily calculated from the width and width of the container), I need to be able to calculate this position number 7 . in row row 2, column 1 .

The width of the container and the element can not always be divided exactly so that the equation should take into account any extra spaces at the end of each line and, naturally, transfer the elements to the next line, as it would in the html float layout.

Thank you in advance

EDIT:

I managed to get the string pretty accurately by doing the following:

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

This is with an index of elements starting at 1, not 0;

+4
source share
2 answers
  • Find the number of elements in one row using gender (line width) / (element width).
  • Divide the index number given by the elements in the row (which you just understood). This will give you a position in the line.
  • Next, find the column position by taking the remainder from step 1 (you can use the module). Multiply the remainder by the number of elements in the row. This will be the column in which it is located.

example: 3 elements in a row, 4th element: gender (4/3) = 1 (row 1) remainder = (4% 3) = 1 (column position)

Be careful what index you start at (be it 0 or 1). This example starts at 1. If you want to start at shift 0, subtract 1 (index number).

+7
source

Something like that?

 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 } 
+4
source

All Articles