Reputation: 2908
I have a container with a specified width of 980px that contains inline-block elements. Each element has a width and height of 140px, which means that each line/row can contain 7 elements before they are pushed down to the next line/row.
<div id="container"><div id="ele1"></div><div id="ele2"></div><div id="ele3"></div><div id="ele4"></div><div id="ele5"></div><div id="ele6"></div><div id="ele7"></div><div id="ele8"></div><div id="ele9"></div><div id="ele10"></div><div id="ele11"></div><div id="ele12"></div><div id="ele13"></div><div id="ele14"></div></div>
Knowing the number of the element, how do I determine with JavaScript (not jQuery) what line/row and what column that element is in? I need to be able to do this for any number of elements, as the number is dynamic and not set by the script.
Upvotes: 1
Views: 136
Reputation: 4180
this might work:
column = Number(yourNumber) % 7
row = Math.floor(Number(yourNumber) / 7)
This supposes you start with 0 then the first element is (0, 0)
Upvotes: 2
Reputation: 74204
If you know the number of the element starting from 0, 1, ... then use the following code:
function getRowColNoFor(elementNo) {
var col = elementNo % 7;
return {
col: col,
row: (elementNo - col) / 7
};
}
Upvotes: 2
Reputation: 227240
If you know that you will have 7 elements across, you can just divide the element's number (starting at 0) by 7 to get it's position.
If you divide the element's number by 7, the "whole number" value is it's row, and the remainder is it's column.
So, to get the position in the grid, you can do this:
function getPositon(index) {
return {
row: Math.floor(index / 7),
column: index % 7
};
}
DEMO: http://jsfiddle.net/UVZ5f/1/
Upvotes: 0