javascriptloopsclicktag

Implementing loop for var names for clickTags


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.


Solution

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