I have this code which works, but it very elementary in my opinion:
var color1Default = $('.layer1').css('fill');
$('#colorbox1').css('background-color', color1Default);
var color2Default = $('.layer2').css('fill');
$('#colorbox2').css('background-color', color2Default);
var color3Default = $('.layer3').css('fill');
$('#colorbox3').css('background-color', color3Default);
I have a variable that is created based on an echoed PHP variable. This variable is an integer value. This value can be different with any given page load. It comes from a db that says how many elements are needed. The html elements are created with a loop in PHP. The class of layer1, layer2, etc are referencing svg paths.
This is how I tried to simply this code:
var numberColors = <?php echo $numColors; ?>;
var colorDefault[];
for (var i = 1; i <= numberColors; i++) {
colorDefault[i] = 'colorDefault' + i;
}
for (var i=1; i <= numberColors; i++){
colorDefault[i] = $('.layer' + i).css('fill');
$('#colorbox' + i).css('background-color', colorDefault[i]);
}
Am I approaching this anywhere near the way I should? Can you please help me not only to make this work, but to understand how to handle this problem in the future with similar problems?
Additionally, the following code is also repeated 12 times changing the numbers by hard coding them. How can I recreate this function to operate dynamically as well?
$('#color1').on('input', function(){
var newValue = $('#color1').val();
if (newValue == ''){
$('.layer1').css('fill', color1Default);
$('#colorbox1').css('background-color', color1Default);
} else {
$('.layer1').css('fill', newValue);
$('#colorbox1').css('background-color', newValue);
}
});
Final Solution including the initial loading of each default color into each of the colorboxes:
var numberColors = <?php echo $numColors; ?>;
$( document ).ready(function() {
const defaultColors = Array.from(
{ length: numberColors },
(_, i) => $('.layer' + (i + 1)).css('fill')
);
const colorBoxes = $('.colorbox');
const colorInputs = $('.colorinput');
$(colorBoxes).each(function (index) {
$(this).css('background-color', defaultColors[index]);
});
colorInputs.on('input', function() {
const $this = $(this);
const index = colorInputs.index($this);
const newColor = $this.val() || defaultColors[index];
$('.layer' + (index + 1)).css('fill', newColor);
colorBoxes.eq(index).css('background-color', newColor);
});
});