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);