For a HTML button:
<button type="button" id="100">100%</button>
I have a java script function, that swaps 2 background colors of that button:
const but1 = document.getElementById("100");
n=0;
but.addEventListener("click", function (){
if (n==0) {
but1.style.backgroundColor = "rgb(225, 165, 0)";
n=1;
} else {
but1.style.backgroundColor = "rgb(225, 165, 0,0)";
n=0;
}
});
Works fine. But i want to create more buttons, and don`t want to copy the same function every time. So to make it more simple, ive written a function that will take parameters , lets say "b" (for buttons),"c1" and "c2" (for colors), and "x" - that represents the "n" value (for every button). So my java script (for the HTML button) with example set of two buttons
const but1 = document.getElementById("button");
n=0;
function colorSwitch (b, c1, c2, x){
if (x==0) {
b.style.backgroundColor = c1;
x=1;
} else {
b.style.backgroundColor = c2;
x=0;
}
}
// orange set
const cOrange = "rgb(225, 165, 0)";
const cOrangeT = "rgb(225, 165, 0,0)";
but1.addEventListener("click", function(){
colorSwitch(but1, cOrange, cOrangeT, n);
});
The problem i have is with "x" parameter. It seems to grab the initial "0" value, then it is set to "1". But when i click the button again the initial value is again "0". So there is no loop and the color doesn't swap.
What am i not understanding in behavior of "x", and how to code it correctly?