Skip to content
Advertisement

How do I return position of an element in flex wrapped row based on click?

I’ve tried and failed to use the nearly perfect answer given here: How to calculate the amount of flexbox items in a row?

The answer given returns the item count only in the top row. But I’m needing to get the position of an element clicked, in any row.

For example, in the below demo, if a user clicked on the box that is highlighted in black, how would I get the value of “2” out?

.grid {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  width: 400px;
  background-color: #ddd;
  padding: 10px 0 0 10px;
  margin-top: 5px;
  overflow: auto;
}

.item {
  width: 50px;
  height: 50px;
  background-color: red;
  margin: 0 10px 10px 0;
}

.active.item {
  outline: 5px solid black;
}
<div id="grid" class="grid">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item active"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

I would assume a solution would not care about wrapping based on container size.

Advertisement

Answer

This is one way of doing it:

document.getElementById("grid").addEventListener("click", function(event) {
  const grid = Array.from(this.children);
  const baseOffset = grid[0].offsetTop;
  const breakIndex = grid.findIndex(item => item.offsetTop > baseOffset);
  const numPerRow = (breakIndex === -1 ? grid.length : breakIndex);
  const el = event.target;
  const el_index = [...grid].indexOf(el);
  const position = (el_index % numPerRow) + 1
  console.log(position);
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement