0

So I am creating buttons in a response to a succcessful AJAX call, and each button needs to call a function with that specific dynamic info. Here is how I am doing it right now:

    for(var i = 0; i < variableNames.length; i++) {

      var getInvButton = document.createElement('button');
      getInvButton.id = 'getInventoryButton';

      console.dir('Add a button with this ID: ' + variableNames[i]);

      getInvButton.addEventListener("click", function(charName, membershipName) {
           console.dir('Test button click: ' + charName);
           getInventoryVar(charName, membershipName);
      } (variableNames[i], 
 result.Response.characters.data[variableNames[i]].membershipId), false);
 }

I can access my variables properly, and the getInventoryVar is called with the right parameters for each button. However, this function is being executed immediately upon it being added.

2
  • First: Ensure that your elements have a unique id. Right now getInvButton has the same id for all variableNames. Second: Do you add the buttons anywhere to your DOM? Commented Apr 29, 2018 at 23:00
  • They button's do not have a unique ID, but they I don't that they need unique ID's. And yes I did add it to the DOM later on in the function. Commented Apr 29, 2018 at 23:33

2 Answers 2

1

You can rewrite your handler like this:

function(charName, membershipName) {
  return function(e) {
    console.dir('Test button click: ' + charName);
    getInventoryVar(charName, membershipName);
  }                           
} (variableNames[i], result.Response.characters.data[variableNames[i]].membershipId)
Sign up to request clarification or add additional context in comments.

2 Comments

This worked! Not 100% sure why though, is it because of the closure aspect of javascript?
It's because that way a function is returned, which is executed on click. By adding (<charname>, <membershipName>) after your function definition, the method gets executed. Therefore you returned the result of the function in your original code instead of the function itself.
0

The functions that you are trying to attach function(charName, memberShipNa... is actually being called when you attach it. You should instead create a new function that calls this function:

getInvButton.addEventListener("click", function() {

    // old function
    function(charName, membershipName) {
       console.dir('Test button click: ' + charName);
       getInventoryVar(charName, membershipName);
  }(variableNames[i], result.Response.characters.data[variableNames[i]].membershipId);

}, false);

(could be more succint, but hey)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.