0

I have been able to create the buttons using the for loop, but on click on a button, it picks the last value in the list of arrays, Why?

//list of propertySidebarItem styles to use to create the buttons
for (var i = 0; i < propertySidebarItem.styles.length; i++) {
  //current property style to use
  var style = propertySidebarItem.styles[i];
  //create the button using the current style
  var btnElement = document.createElement('button');
  btnElement.className = 'btn ' + element.tagName + style.name;
  //on click of any button, display the button properties
  btnElement.onclick = function () {
    //at this stage i am getting the last value in the propertySidebarItem.styles array
    console.log(btnElement);
  };
}
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • read [mdn closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) to find a solution to how create a scope and save the value `onClick` will use when the callback function of it is called. – kankan256 Nov 19 '21 at 11:42
  • tl;dr: There is a single `btnElement` variable and all functions refer to the same variable (which of course can only have a single value). In JavaScript closures resolve free variables when the function is called, not when the function is defined. – Felix Kling Nov 19 '21 at 11:43

0 Answers0