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:


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


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

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


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');
one_class = "button blue"


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