Utilize SCSS and JavaScript to implement dynamic color variations and opacity adjustments

I am working on a feature where users can personalize the theme by selecting their own colors from a dropdown menu. My task as a developer is to apply different shades based on the chosen color.

For example, if the user chooses Green, I would use solid Green for the primary header, Green with 60% opacity for table headers, and Green with 50% opacity for active/selected table rows.

I have attempted the following approach, but passing a variable to RGBA does not seem to impact the background color:

CSS

:root {
    --color: #008000;
    --alpha: 0.5;
}

#primary-header{
    background-color: rgba(var(--color));
}

#table-header{
    background-color: rgba(var(--color), var(--alpha));
}

Answer №1

It seems like you are looking to dynamically manipulate CSS using JavaScript.
Check out this live example that demonstrates how you can change the color and opacity of CSS variables.

<!DOCTYPE html>
<html>
  <head>
    <style>
    :root {
    --currentColor: orange;
    --op: 0.9;
}
a {
  color: var(--currentColor)
  opacity: var(--op);
}
div {
  width: 100px;
  height: 100px;
  background-color: var(--currentColor);
  opacity: var(--op);
}
    </style>
  </head>
  <body>
    <select id="combo" onchange="changeColor()">
      <option>orange
      </option>
      <option>green
      </option>
      <option>red
      </option>
      <option>blue
      </option>
    </select>
    <div>
    </div>
    <select select id="combo2" onchange="changeColor()">
      <option>0.9</option>
      <option>0.8</option>
      <option>0.1</option>
      <option>0.5</option>
    </select>
    <script>
      function changeColor()
      {
        // get the color value from the select control
        var color = document.getElementById("combo").value;
        // apply css change
        document.documentElement.style.setProperty('--currentColor', color);
        // get the opacity value from the select control
        var color = document.getElementById("combo2").value;
        // apply css change
        document.documentElement.style.setProperty('--op', color);
      }
    </script>
  </body>
</html>

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

Execute jQuery code only when a child element within the parent container is clicked

Within a div section, I have included various child controls like dropdowns and check boxes. I am seeking to implement some jQuery code that will be triggered when any of the child elements are clicked, excluding clicks on the empty space within the div. ...

I am struggling to access the input file data in my controller while attempting to send it over AJAX

Currently, I am utilizing Laravel 3 and incorporating a user comment via AJAX. The issue I'm facing is related to adding images to the comment, as I am encountering difficulty getting the File Data to pass through. Moreover, when I set processData to ...

Utilizing ASCX to trigger JavaScript functions within an ASPX page

I created a user control named MyListSelect.ascx that contains a list of radio buttons... <%@ Control Language="C#" %> <select> <option disabled selected>Select Options</option> <option> option 1 </opti ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...

What is the reason for Nightwatch running each .js file as a Child process? Could it be due to alterations in the configuration settings

Recently, I've been experiencing an issue when running Nightwatch.js where my console is spawning child processes for every .js file in each folder and subfolder. Multiple Chrome instances are opening along with them and even the module folders with r ...

ways to change the font color style of a header element using css

Below is the HTML code that I need to work with: <h5 class="post-title">Welcome To The Site</h5> I am attempting to change the font color to red using this CSS: .post-title{ color:red ! important; } However, my attempt was unsuccessful ...

Looking to loop through the JSON objects saved in an array of JSON data in local storage

I have reviewed various resources, including Iterate through nested json object array, but none of them seem to address my specific situation. The current challenge I am facing involves storing multiple JSON objects in an array within local storage. This ...

Define the term "Parse Error" as it pertains to CSS

i'm encountering an issue while attempting to validate my CSS. Despite trying to validate using direct input (copy and paste), the error persists. In my pursuit to find a solution, I researched on Google only to discover that it could be related to sp ...

What is the best way to show a specific range of months in the primeng calendar (p-calendar)?

Struggling to showcase a timeframe spanning two months in p-calendar, but without any luck. For instance, I aim to exhibit dates only between the mid of one month and the mid of the following month. I prefer accomplishing this using reactiveForm with fo ...

Retaining the initial div container and removing all others that match the specified search criteria

<div data-attrType="time"> <div class="box"> <div class="inputBox"> <div class="input-text-grp"> <input name="startTime" type="text"> </div> </div> &l ...

Tips for creating case-insensitive query string values in angularjs?

After reading about the case sensitivity of query string keys from here, I realized my query pertains to the case sensitivity of query string values. Is there a way to make query string values case insensitive? Is it possible to receive the same result wh ...

Which is better for creating a partial panoramic view: iPhone panorama, three.js, or Pannellum

I have been facing this issue for the past 2 weeks, trying various JavaScript libraries like ThreeJS, but without any luck. Pannellum seems promising to me, especially in its support for partial panoramas with just one photo. My goal is to create a panor ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

problem when using directive $compile with encapsulating HTML

I'm currently working on developing a directive that, when declared like this: <input my-directive show-button-bar="true" ng-model="fooBar"\> It should generate the following HTML structure: <div on-toggle="toggled(open)" is-open="dpM ...

utilizing PhoneGap for transforming a website into a mobile application

My website is already built and fully functional using ajax, jquery, html, and php. When converting it over to PhoneGap, I'm wondering if I need to create all new php files to attach to the PhoneGap server, or if I can just use the existing files from ...

Tips for getting rid of NavLink styling when Routes are not selected

I need assistance in restoring the default style of NavLink as shown in the screenshot below. The color should be white and without underlines. Here is my code snippet: Home is currently selected as the default path, and the activeClass property is functio ...

Lazy loading images using the lazysizes plugin allows the browser to calculate the total page size without waiting for the images to

Having trouble with the lazysizes plugin and srcset on a fluid layout. The page keeps extending as you scroll instead of loading to the correct length You can see my attempt using the bootstrap framework in this CodePen demo After much research, it seems ...

Step-by-step guide on uploading a template in unlayer-react-email-editor

<EmailEditor ref={emailEditorRef} onReady={onTemplateReady} /> const onTemplateReady = () => { try { const templateJson = htmlToJSON(savedData?.email?.content); console.log({ templateJson }); emailEditorRef?.current?.editor?. ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...