0

I have something that I would like to convert from jquery to js.

I am using js to create 12 li elements which when clicked gets the index number, in jquery I used the .index() function to achieve this,

var month = $(".calenderApp__calender__allMonths__month"),
    startMonth;

$(month).on('click', function () {
    startMonth = $(this).index() + 1;
});

How would I do this is vanilla js, I have gotten as far as

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
    startMonth;

for (var i=0; i<month.length; i++) {       
    month[i].addEventListener("click", function () {
        startMonth = this; //returns full html element, just need index number
    });
}
Sai
  • 801
  • 3
  • 10
  • 27
  • startMonth = i returns 12, i need it to return the index of the element clicked – Sai Aug 25 '16 at 10:13

2 Answers2

2

Just store the index in the element.

var month = document.querySelectorAll(".calenderApp__calender__allMonths__month"),
    startMonth;

for (var i=0; i<month.length; i++) {
    month[i].index = i;
 
    month[i].addEventListener("click", function () {
        alert(this.index+1);
    });
}
<ul>
  <li class="calenderApp__calender__allMonths__month">Jan</li>
  <li class="calenderApp__calender__allMonths__month">Feb</li>
  <li class="calenderApp__calender__allMonths__month">March</li>
  <li class="calenderApp__calender__allMonths__month">Apr</li>
</ul>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
2

This is the traditional closure in a loop problem. Indeed, this use case was the original use case that people asked about before ajax became popular. As such you can use the traditional solution:

for (var i=0; i<month.length; i++) {
    (function(j){
        month[i].addEventListener("click", function () {
            startMonth = j; // j is the captured value of i
        });
    })(i); // capture value of `i` here to break closure
}

As for why this happens read this: Please explain the use of JavaScript closures in loops or any of the dozens of pages about closures in loops on SO or elsewhere.

Community
  • 1
  • 1
slebetman
  • 109,858
  • 19
  • 140
  • 171