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...
testMe('test')immediately calls thetestMefunction when that line of code runs. You need to pass a function toaddEventListenerwhereas you are currently passingundefined(the return value oftestMe). 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')