My index page is quite straightforward - it has buttons that when clicked, randomly change the colors displayed on the background circle divs. The code I've written works well, but it's a bit repetitive; I ended up creating a separate function for each button, and they all look very similar except for the variables they use.
I've been contemplating consolidating these functions into one to avoid redundancy, but I'm struggling to find a way for the clicked button to access the correct variable and alter the background colors accordingly. For instance, take a look at the function for the first button, which uses the colorList variable to change the colors within the gray spectrum:
var colorList1 = [//array of 20 colors]
var colorList2 = [//array of 20 colors]
var colorList3 = [//array of 20 colors]
var colorList4 = [//array of 20 colors]
// .choice-1 represents the div class for the first button
$(".choice-1").on("click", function() {
blankSlate();
colorList = colorList1;
$("[id^='nav']").css("background-color", colorList[1]);
$("#colorChoice").css("background-color", colorList[1]);
});
I attempted to write some code that would extract the number from the class name and set it as a variable accessible to the primary function, like so:
var buttonVar = $("button").attr[0].nodeValue; // get full name of nodeValue
var btnChoice = buttonVar[buttonVar.length-1]; // access number at end of class name
$("button").on("click",function() {
$('.choice' + btnChoice).on('click', function(){*/
blankSlate();
colorList = colorList + btnChoice;
$("[id^='nav']").css("background-color", colorList[btnChoice]);
$("#colorChoice").css("background-color", colorList[btnChoice]);
});
...but I'm uncertain if this approach is correct, and I'd greatly appreciate advice on how this type of refactoring is typically approached.
If you're interested in seeing my work in action, here's a Codepen link showcasing the functionality along with the HTML, CSS, and the rest of the JavaScript code: http://codepen.io/a6ftcruton/full/Beizu