Manipulating CSS styles through Javascript with passed parameters

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?

Answer №1

1. You need to fix the hexToRgb function as it is returning a broken value without closed brackets.

It's also advisable to use rgb instead of rgba, but both will work. Remember that rgba expects 4 parameters, including alpha.

Replace

    return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',');

with

    return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';

2. The .btn-primary class in Bootstrap has styles with !important priority. If you need to override it, you should also use !important.

To do this, add important as the third argument in the setProperty function.

Modify

  element.style.setProperty('background-color', this.primaryColor);
  element.style.setProperty('border-color', this.primaryColor);

to

  element.style.setProperty('background-color', this.primaryColor, 'important');
  element.style.setProperty('border-color', this.primaryColor, 'important');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for refreshing an html table without affecting the scroll location?

HTML: <div class="html_table"></div> # Within the html body tag. Utilizing Ajax function to retrieve table data. var $html_table= $('.html_table'); function ajaxCallFunction() { $.ajax({ type: 'POST', ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Designing functions with HTML

I have been working on creating a Coffeescript function that incorporates common HTML for an object that is frequently used on my page. To make the content dynamic, I am passing a variable to the function which will be replaced each time it is called. Unfo ...

Quickly Share Documents within a Folder

I currently have a server set up with the following file structure: - index.js /client -index.html -about.html -signup.html -style.css Within the index.js file, I have implemented an express server. When the user navigates to /, it should display the ...

Using Radio Buttons in a jqGrid Interface

Currently, I am attempting to integrate radio buttons within a jqGrid framework. I am aware that a custom formatter can be utilized for this purpose. Below is my code snippet, however, it fails to provide information on which radio button is selected or if ...

Retrieve element attributes and context inside a function invoked by an Angular directive

When working with a directive definition, you have access to the $element and $attrs APIs. These allow you to refer back to the element that called the directive. However, I'm curious how to access $element and $attrs when using a standard directive l ...

A TypeScript function that returns a boolean value is executed as a void function

It seems that in the given example, even if a function is defined to return void, a function returning a boolean still passes through the type check. Is this a bug or is there a legitimate reason for this behavior? Are there any workarounds available? type ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Error message: Cannot establish the attribute 'next' on the string '/:id'

I encountered an error while trying to develop an API for a travel company. The error message "TypeError: Cannot create property 'next' on string '/:id'" keeps popping up, even though all the necessary functions are already created. con ...

Ways to eliminate hover effect in CSS

I have a text that is currently displayed as a hyperlink, and some CSS code is causing it to underline and become bold when hovered over. I want to remove the hyperlink, but still keep this style by default without needing to hover over the text. Here is m ...

Injecting configurable middleware dependencies in Nest.js allows for dynamic customization of middleware

While many tutorials demonstrate how to inject providers into dynamic modules, most of them only focus on services and not middleware. The challenge arises when attempting to create reusable middleware that also requires injected providers. For instance, ...

Struggling with parsing JSON strings into PHP arrays

I'm looking to transmit a JSON string using JavaScript and later convert it into an array using a PHP encoding function. After successfully converting the string in JavaScript and transmitting it via Ajax to a PHP page, I am encountering difficulties ...

IE is causing issues with the transition

How come the transition doesn't seem to be working in this IE example? https://codepen.io/littlesnippets/pen/rxKBWq I've searched for solutions and tried adding recommended meta tags, doctype, etc., but nothing seems to work... /* This code ...

Two Elements Linked Together

I'm facing an issue with my interconnected React components. Despite being separate entities, they appear to share some styling attributes which I find puzzling. The main problem lies in the footer component as it seems linked to another component, p ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

Changing color of the collapsible icon and content when hovered over

Currently, I am working on creating collapsible content for a FAQ dropdown. The button has a 'plus' icon which changes to a 'minus' icon when clicked. My goal is to change the color of the pre-clicked 'plus' icon to white when ...

Guide on applying a filter to the items in a listbox using the input from a text box

In my HTML form, I have the following elements: 1) A list box containing filenames: s1.txt2013 s2.txt2013 s3.txt2012 s4.txt2012 2) A text box where the user enters a pattern (e.g. 2013) 3) A button By default, the list box contains the 4 file ...

``How does React facilitate the passing of properties from an API to a component?

I have two components - parentA and childB. I am trying to achieve a functionality where clicking a button in parentA triggers a function to fetch data from an API and then display it in the B component. On the surface, it seems like a simple task. Parent ...

Unable to store form data in a JSON file

i need help with the json data file called groups.json { "groups" : [ { "pname" : "group1", "remarks" : "best" }, { "pname" : "group2", "remarks" : "not the best" } , { "pname" : "group3", ...