I’m making a basic color generator that generates a random hex or RGB color depending on which button is pressed. I’ve made a constructor function that runs each time a button is pressed, generating a new color with a bunch of methods for generating light/dark variations, translating between color spaces, etc.
My UI has 3 buttons: hex, translate, and RGB. I currently have code written on the event listener for translating that will change between hex/RGB, but it would be more concise if I could use a method from the same color object generated when I click hex/rgb.
Currently, I have the following code when I click either the hex or rgb buttons:
hex.addEventListener (‘click’) function () {
const newColor = new Color();
setStylesHex(newColor);
}
In an ideal world, I would be able to have something like this on the translate button (using the newColor variable generated above), but I am running into scope issues:
trans.addEventListener (‘click’, function() {
if (head.innerText[0] === 1) {
setStylesRGB(newColor);
} else {
setStylesHex(newColor);
}
})
I haven’t really tried anything besides reproducing my translator code on the event listener for the translate button. I’m really lost for how to get my desired functionality and would appreciate any help.
CodePudding user response:
Place the declaration for newColor
in a scope where both functions can access it:
let newColor;
hex.addEventListener (‘click’) function () {
newColor = new Color();
setStylesHex(newColor);
}
trans.addEventListener (‘click’, function() {
if (head.innerText[0] === 1) {
setStylesRGB(newColor);
} else {
setStylesHex(newColor);
}
})