I'm going through a web development bootcamp course and doing some extra work on one of our projects. We built an RGB Color Guessing game and I'm converting it to a Hex Color Guessing Game. While there are plenty of examples online that show code I can copy and paste to make this conversion, I'd rather write my own with an understanding of how the code functions. So my question isn't so much "How do I do this one thing?" as it is "What am I doing wrong right now and why can't I do it this way?" and then show me an example of something that works.
I've tried a few different methods I've seen online, but in each application I am not doing the logic properly as I receive "cannot set property of undefined" or "splilt() is not a function) etc.
for(var i = 0; i < squaresVar.length; i++) {
//add click listeners to squares
squaresVar[i].addEventListener("click", function() {
//convert RGB clickedColorVar to hex value
var clickedColorVar = this.style.backgroundColor;
function rgbToHex(clickedColorVar) {
//this is where I check that the function is running and that the var is selected
console.log("inside the rgbToHex function" + clickedColorVar);
//this bit is where I am confused. I am probably not using it right.
var clickedColorVarArray = clickedColorVar.slice(clickedColorVar.indexOf("("), clickedColorVar.indexOf(")")).split(",");
//if I can get the previous line of code to work, these rgb variable values should be extracted into an array I can then selectively convert into hex values, but I haven't made it this far since before we get here the console returns "split is not a function"
var r = clickedColorVarArray[0];
var b = clickedColorVarArray[1];
var g = clickedColorVarArray[2];
return "#" + makeHex(r) + makeHex(g) + makeHex(b);
}
//Here is the function we are calling to convert the rgb values into 2 digit hex values
function makeHex(x) {
var hex = x.toString(16);
//I don't understand this bit either, why aren't we checking for 2 digits?
//or is this checking for one digit and then adding a 0?
return hex.length == 1 ? "0" + hex : hex;
}
//and at last here is where I call the rgbToHex function and pass it the clickedColorVar (which is an rgb color)
rgbToHex(clickedColorVar);
I was expecting that I could get three different values, one for r, g, and b, but the way I am trying to use the .slice(), indexOf(), and .split() methods must be wrong.
Here it is in codepen: https://codepen.io/KD-Neeley/pen/PooNvWQ