1

var trackMeLinks = document.querySelectorAll('.track-me-one');

if (trackMeLinks.length) {
  for (var link of trackMeLinks) {
  link.addEventListener('click', testMe('test'));
  }
}

function testMe(msg) {
 console.log(msg);
}
<a class='track-me-one' href='#'>click me</a>
<a class='track-me-one' href='#'>click me 2</a>

I'm trying to pass a very simple variable into an event listener inside a for loop. I actually can't figure out why it's not working despite it seeming very simple.

When clicking on any link, it should simply log 'test' to the console. Instead, the logs are run when the dom loads.

Why does this happen, and what is the fix for this?

I know that I could remove the brackets after testMe is called, but then I cannot pass in a variable. Thanks...

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • 1
    Try this link.addEventListener('click', () => testMe('test')); or link.addEventListener('click', function() { testMe('test');}); – Florim Maxhuni Jan 22 '20 at 11:24
  • 1
    `testMe('test')` _immediately_ calls the `testMe` function when that line of code runs. You need to pass a _function_ to `addEventListener` whereas you are currently passing `undefined` (the return value of `testMe`). If you want to "bake in" a value to that function, you can either use a lambda function `() => testMe('test')` or `.bind()`: `testMe.bind(null, 'test')` – JLRishe Jan 22 '20 at 11:24
  • Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – Jakub Hubert Jan 22 '20 at 11:26

2 Answers2

3

var trackMeLinks = document.querySelectorAll('.track-me-one');

if (trackMeLinks.length) {
  for (var link of trackMeLinks) {
  link.addEventListener('click', () => testMe('test'));
  }
}

function testMe(msg) {
 console.log(msg);
}
<a class='track-me-one' href='#'>click me</a>
<a class='track-me-one' href='#'>click me 2</a>
kooskoos
  • 4,622
  • 1
  • 12
  • 29
1

You passed your function and call it at the same time, that is way You've got message into your console.

You may wrap calling your function with clouser function like this

var trackMeLinks = document.querySelectorAll('.track-me-one');

if (trackMeLinks.length) {
  for (var link of trackMeLinks) {
        link.addEventListener('click', function () {
          testMe('test');
        });
  }
}

function testMe(msg) {
    console.log(msg);
}
Vladimir
  • 161
  • 2