0

I try to add two event listeners to the same DOM elements like this:

const rows = document.querySelectorAll(`.row`);

for (let i = 0; i < rows.length; i++) {
    rows[i].addEventListener(`touchend`, (e) => {
        console.log(i)
        if (documentClick) {
            const code = rows[i].dataset.code;
        }
    });

    rows[i].addEventListener(`click`, (e) => {
        console.log(i)
        const code = rows[i].dataset.code;
    });
}
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>
<div class="row">x</div>

When I check the index of clicked element in console it gives me different index. How can it be and why does it happen?

enter image description here

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Nastro
  • 1,719
  • 7
  • 21
  • 40
  • 1
    I think some context might be necessary. Keep in mind `touchend` is supposed to fire only on touch screens. Are you sure there isnt something else logging the 37 number? – Marco Scabbiolo Mar 12 '20 at 13:48
  • Yes, I'm sure. Just checked. I have a simple JS file with 2 console.log functions in it. – Nastro Mar 12 '20 at 13:50
  • @Nastro - The code in the question cannot do that, the same `i` is used by both `console.log` calls (and is specific to each loop iteration). So something else is going on. :-) – T.J. Crowder Mar 12 '20 at 13:58
  • The rows are in the div with overflow. I noticed that the index is the same until I scroll the rows. Any thoughts about it? – Nastro Mar 12 '20 at 14:00
  • @PoulBak what does it mean? Can you give more details? – Nastro Mar 12 '20 at 14:36
  • @PoulBak - Not with `let` declared in the `for` as used by the OP above. You're thinking of `var` (or `let` declared **before** the `for`). **Not** having the closure-in-loops problem is one of the good things about `let` declared in `for` loops. – T.J. Crowder Mar 12 '20 at 15:13
  • I removed container.scrollTo(0, 0); from event handler function and it's start to work... Something with scroll definitely – Nastro Mar 12 '20 at 15:14

0 Answers0