Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript adding addEventListener dynamically to elements but the same function is called for all

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading