I need a feature that allows users to pick the color of the buttons displayed on the website. Currently, I am working with Angular 6 and JavaScript to achieve this functionality. I am focusing on setting the primary color, affecting buttons with the Bootstrap class of .btn-primary.
Here's how it works: I have a color wheel that sends hex values to a function when the user makes a selection. The function then converts the hex value to RGB and gathers all the .btn-primary buttons using querySelectorAll. It attempts to loop through each button and set the background and border colors to match the selected color.
To implement this in HTML, you will need to include the ngx-color-picker and import the Bootstrap package:
<button class="btn btn-primary">Save changes</button>
<div class="form-group mt-2">
<label class="d-block" for="setPrimaryColor">Set primary color</label>
<input
(colorPickerChange)="setPrimaryColor($event)"
id="setPrimaryColor"
[(colorPicker)]="color"
[style.background]="color"
[cpOutputFormat]='auto'/>
</div>
For the TypeScript/JavaScript code in Angular 6:
heroGradient1 = 'rgba(0, 0, 0, 0.1)';
heroGradient2 = 'rgba(0, 0, 0, 0.8)';
primaryColor: string = '';
setPrimaryColor(color) {
this.heroGradient1 = this.hexToRgb(color) + ', 0.1)';
this.heroGradient2 = this.hexToRgb(color) + ', 0.8)';
this.primaryColor = this.hexToRgb(color);
const primaryBtns = document.querySelectorAll<HTMLElement>('.btn-primary');
console.log(primaryBtns)
primaryBtns.forEach(element => {
element.style.setProperty('background-color', this.primaryColor);
element.style.setProperty('border-color', this.primaryColor);
});
}
hexToRgb(hex){
var c;
if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
c= hex.substring(1).split('');
if(c.length== 3){
c= [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c= '0x'+c.join('');
return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',');
}
throw new Error('Bad Hex');
}
Although the console log shows that querySelectorAll is selecting all .btn-primary buttons, the for loop seems to be failing to modify the background and border colors. Can anyone provide assistance with this issue?