0

What I would like to achieve with the javascript below is:

That when one of the divs is clicked the correct parameter (in this case the number of the div) will be sent to the callback function and executed (in this case the callback function will display the number in the console)

However, the callback function is getting an undefined parameter. If I replace the anArray[i] in the newElement.addEventListener('click',function(){callback(anArray[i])}); with 'hello'. I see the word hello written in the console, but I want the callback function to have different values for different divs.

Please no JQuery solutions, pure js only

Thank-you

function doThis(anArray,callback){
  for(var i = 0;i < anArray.length;i++){
    var newElement = document.createElement('div');
    newElement.innerText = anArray[i];

    //if I use this line below I aways get undefined in the console log. I want it to show the value of anArray[i]
    /*1*/  newElement.addEventListener('click',function(){callback(anArray[i])});

    document.body.appendChild(newElement);
  }
}

var showTheValue = function(value){
  console.log(value);
}

doThis([1,2,3,4,5,6,7,8,9,10],showTheValue);

1 Answer 1

1

By the time your callback is evaluated, i points to an index beyond the length of your array. To correct for this, create a closure for the callback function.

newElement.addEventListener('click',
  (function(arrayItem) {
    return function(){ callback(arrayItem); };
  })(anArray[i]));

If you do not need to support older browsers (IE8 and older) you can use ecmascript5 function binding.

newElement.addEventListener('click', callback.bind(window, anArray[i]));

More information on Function.bind

Sign up to request clarification or add additional context in comments.

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.