I am trying to get the elements index on the first click. I am not sure what is going on with my eventListener but it only seems to work after i have clicked once on the element.
I tried changing the scope of the listener and debugging directly through "getListeners" of the element but to no avail.
I also tried to separate the listeners instead of nesting it but then it jsut doesn't work.
const directory = document.querySelector('.directory')
, card = document.getElementsByClassName('card')
;
directory.addEventListener('click', () =>
{
if (card)
{
for (let i = 0; i < card.length; i++)
{
card[i].addEventListener('click', () =>
{
console.log(i);
});
}
}
})
.card {
cursor: pointer;
margin: 10px 0;
text-align: center;
}
<main class="directory">
<div class="card">0</div>
<div class="card">1</div>
<div class="card">2</div>
</main>
if the .card element is clicked then "i" should be printing to the console.
However, always the first click produces no console print.