Using variables in onclick (keep old variable value even if changed later)

Tags: , , ,



I have a problem where I need to dynamically add onclick events in javascript buttons using variables that the user gives. The problem: These variables will change, but I dont want the onclick events to all change!!

I wrote up a mini example that mimics the setup I have (but obviously getting rid of unnecessary parts and therefore looks a bit silly).

NOTE: I tried to clone the variable using these:

1) clone = Object.assign({}, old);

2) clone = JSON.parse(JSON.stringify(old);

Neither worked

Here is the codepen: https://codepen.io/samuel-solomon/pen/ExPqdpM

HTML:

<div id="1"></div>

CSS

button {
  width: 50px;
  height: 50px;
}

.blue{background-color: blue;}
.black{background-color: black;}

Javascript

btn1 = document.createElement('button');
var one_class = "button black";
btn1.className = one_class;
btn1.addEventListener('click', function() {btn1.className = one_class;})
add_first = document.getElementById('1');
add_first.appendChild(btn1).html;
one_class = "button blue"

Answer

You can use Function#bind to designate a specific value as the first parameter of the event handler. This will work as one_class is a string primitive.

btn1.addEventListener('click', function(cls, event) {
       btn1.className = cls;
}.bind(null, one_class));


Source: stackoverflow