Mathias Mathias - 5 months ago 9
Javascript Question

Understanding listening for click event from list of nodes using Javascript

So I had built a Boostrap page whereby I have an array (or list) of child nodes for selection from a dropdown menu. I wanted to detect which node had been clicked and then display the value in the new value in the menu button.

Initially I tried to detect a click event via the following code:

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

menu[i].firstchild.innerHTML.addEventListener("click", function(){

// Assign value of node clicked on to button
button.childNodes[0].nodeValue = menu[i].firstChild.innerHTML;

});
}


However the above does not work, and menu[i].firstChild.innerHTML always seems to be undefined. I was wondering why this is the case?

I found a solution to the problem using this code from another question:

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

(function(index) {

console.log(menu[index]);
menu[index].addEventListener("click", function(){

for (var x = 0; x < menu.length; x++){

if (menu[x] == this){

//alert(x);
//console.log(button.childNodes[0].nodeValue);
button.childNodes[0].nodeValue = menu[x].firstChild.innerHTML;
}
}


}, false);

})(i);
}


From: Detecting which node was clicked in javascript

However, I fail to really understand what is going on here. What are we actually passing into the first for loop? This seems to be (function(index){//code})(i); I can't say I have seen this syntax before. Then what is the purpose of the second for loop?

I would be very grateful if a better programmer than myself could explain to me what is going on here.

Kind Regards,

Answer

In your initial code you addEventListener to innerHTML which is string and is deaf to click. Easy fix is possible.

for (var i = 0; i < menu.length; i++){
       menu[i].firstchild.addEventListener("click", function(){
            // Assign value of node clicked on to button 
            //**this** is what was menu[i].firstChild
            //button is hopefully in global scope.
            button.childNodes[0].nodeValue = this.innerHTML;
       });
 }