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...

3
  • 1
    Try this link.addEventListener('click', () => testMe('test')); or link.addEventListener('click', function() { testMe('test');}); Commented Jan 22, 2020 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') Commented Jan 22, 2020 at 11:24
  • Does this answer your question? addEventListener calls the function without me even asking it to Commented Jan 22, 2020 at 11:26

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.