0

I have created a list using a for loop and want to add an event listener to each of them, so that when each item is clicked, it's logged in the console the item number (e.g. if list item 1 is clicked, console log returns the variable currentNumber as 0).

However, with my current code, all I'm getting in the console log is "4". Can someone please help me with this? Thank you.

 for (i = 0; i < tipsCatalog.length; i++) {
     var newCategory = document.createElement('li');
     newCategory.id = "sMonTipHeadline-" + [i];
     newCategory.className = "sMonTipHeadline";
     newCategory.innerHTML = tipsCatalog[i].tipHeadline;
     catalogContainer.appendChild(newCategory);
 }

 var currentNumber = [];

 for (i = 0; i < tipsCatalog.length; i++) {
     currentNumber[i] = i;
     tipsCatalogList[i].addEventListener('click', function() {console.log(currentNumber[i])});
 }
Chunky Low
  • 69
  • 7
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Patrick Hund Aug 20 '19 at 09:42

1 Answers1

0

I would try to add the number inside an element's attribute and then take it from there when you need it.

tipsCatalogList[i].addEventListener('click', function() {console.log($(this).attr('yournumber'))});
Jorge
  • 831
  • 13
  • 18