Implementing loop for var names for clickTags

96 Views Asked by At

Need to add for a banner three clickTags which have names like clickTag1, clickTag2,clickTag3. Now the code looks like this:

for(var i = 1; i <= 3; i++) {
    document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
        window.open(clickTag2, '_blank'); //here I want clickTag look like clickTag + i, but its not working.
    })
  }

So the question is how to loop var names so I wont need to put it manually, like it is now.

3

There are 3 best solutions below

2
gyre On BEST ANSWER

The cleanest way to solve this problem would be to use an Array.

[, clickTag1, clickTag2, clickTag3].forEach(function(e, i) {
    document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
        window.open(e, '_blank');
    })
})

An alternative method: if your clickTags are global variables, you could always access them as global properties of the window object:

for(var i = 1; i <= 3; i++) (function (i) {
    document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
        window.open(window['clickTag' + i], '_blank')
    })
)(i)

The additional wrapping function fixes the closure bug mentioned in the comments above.

5
TheValyreanGroup On

You want to use an array for this. An array is an indexed list of values.

var clickTags = ["","www.nba.com","www.nhl.com","www.nfl.com"];
for(var i = 1; i <= 3; i++) {
    document.getElementById('Destination_cta_' + i).addEventListener('click', function() {
        window.open(clickTags[i], '_blank'); //here I want clickTag look like clickTag + i, but its not working.
    })
}

Notice since you are starting your loop at 1 instead of 0, i've added a blank entry for index 0 of the clickTags array.

0
Julien Zakaib On

Why it is not currently working the way you intend :

for (var i = 1; i <= 3; i++) {
  // During your first loop there is a local variable `i` whose value is 1
  document.getElementById('Destination_cta_' + i)
    // Here you pass an anonymous function as the second argument to addEventListener
    // This creates a closure, which means the function's context includes variables
    // that were in scope when it was created. Right now we have the `for` loop's variable
    // `i` in the current scope, so the function keeps a *reference* to that variable.
    .addEventListener('click', function() {
     
      // When this get executed in the future, the function has to know about the variable `i`,
      // and thankfully there is a reference to it in this function's closure. But remember that
      // the for loop executed 3 times, using that same variable. That means that every function
      // was created with a closure that is keeping a reference to the same variable, whose final 
      // value after the loop finished, was 4. 
      window.alert('clickTag' + i);  // Will always alert 'clickTag4' no matter which is clicked
  })
}
<div id="Destination_cta_1">1</div>
<div id="Destination_cta_2">2</div>
<div id="Destination_cta_3">3</div>

How to solve this problem ?

Make sure each addEventListener call gets a function with the correct value in a closure of its own. The way to do this is to use an immediately invoked function expression to which you pass in the value you want :

for (var i = 1; i <= 3; i++) {
  var element = document.getElementById('Destination_cta_' + i)

  element.addEventListener('click', (function(index) {
    // This function is now a closure with a reference to index
    return function() { 
      window.alert('clickTag' + index);
    }
  })(i)) // calling the anonymous function with the current value of `i` binds that value
         // to the function's scope
}
<div id="Destination_cta_1">1</div>
<div id="Destination_cta_2">2</div>
<div id="Destination_cta_3">3</div>