0

I have a script that is looking up an array called taggedElements from local storage. I iterate over the elements and then based on the properties I bind a click event to the element using an anon function. The issue that I am having is that the click event is bound but when I click the element the logCustomEvent function is always being passed the last "props" value so for example, both a tags fire the logCustomEvent function but when I console log the props value I see SpecialEvent 2 logged for both elements. If I add a more items to the array it seems to only use the last value in the function call.

My array looks something like this

let taggedElements = 
[
    {"cssSelector" : "#app > div > a", "props" : "SpecialEvent 1"},
    {"cssSelector" : "#app > div > p > a", "props" : "SpecialEvent 2"}
]

I iterate over the array and bind the click event like so

for(var elem of taggedElements){        
    let el = document.querySelector(elem.cssSelector);
    if(el){
        el.addEventListener("click", function(){
            logCustomEvent(elem.props)
        });
    }
}

The output in this example is two links on the page each with a click event that ideally would call the logCustomEvent function with a specific value. What is happening is two links with a click event that call the logCustomEvent function but both using the props value of the last item in the array

user1735894
  • 323
  • 4
  • 16

1 Answers1

3

See the difference between var and let/const I believe that it is the issue. See this question: What is the difference between "let" and "var"? . I beilive if you replace var in your for loop with let your issue will be resolved.

I recommend checking the documentation on mdn for further information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Tim Nimets
  • 348
  • 2
  • 9