Is it possible to modify CSS animations using a variable passed from typescript?

Looking for a way to streamline my animations in the .ts file so that I can use a single block of code to change the hardcoded RGB values with a variable called this.fillColor. Each animation is currently set up separately for different elements, but they all essentially do the same thing with just a color variation.

#loading {
    animation-name:             changing;
    animation-duration:         4s;
    animation-direction:        alternate;
    animation-iteration-count:  infinite;
  }

  @keyframes changing {
      0% {
          fill:this.fillColor;
          width: 20px;
      }
      100% {
          fill: this.fillColor;
          width: 200px;
      }
  }

  #loading2 {
    animation-name:             changing2;
    animation-duration:         4s;
    animation-direction:        alternate;
    animation-iteration-count:  infinite;
  }

  @keyframes changing2 {
      0% {
          fill:this.fillColor;
          width: 20px;
      }
      100% {
          fill: this.fillColor;
          width: 200px;
      }
  }

Answer №1

If you want to dynamically set fill colors using CSS variables/custom properties, you can achieve that easily. The var() function's second argument allows you to specify a fallback/default value if the CSS variable is not defined.

For instance, if you wish to customize the start and end fill colors of #loading, you can do so like this:

@keyframes changing {
    0% {
        fill: var(--loading-fill-from, rgb(105,105,105));
        width: 20px;
    }
    100% {
        fill: var(--loading-fill-to, rgb(250,230,0));
        width: 200px;
    }
}

This code defines the changing keyframe with default fill colors of rgb(105, 105, 105) for the start and rgb(250, 230, 0) for the end. It also allows optional customization through --loading-fill-from and --loading-fill-to custom properties.

You can set these custom properties on the root element since CSS variables are inheritable:

document.documentElement.style.setProperty('--loading-fill-from', YOUR_COLOR_HERE);

Below is a proof-of-concept example (written in ES6 JS, but adaptable to TypeScript):

const varNames = ['loading-fill-from', 'loading-fill-to', 'loading2-fill-from', 'loading2-fill-to'];
document.querySelector('#btn').addEventListener('click', () => {
  for (let varName of varNames) {
    document.documentElement.style.setProperty(`--${varName}`, document.querySelector(`#${varName}`).value);
  }
});
#loading {
    animation-name:             changing;
    animation-duration:         4s;
    animation-direction:        alternate;
    animation-iteration-count:  infinite;
}

@keyframes changing {
    0% {
      fill: var(--loading-fill-from, rgb(105,105,105));
      width: 20px;
    }
    100% {
      fill: var(--loading-fill-to, rgb(250,230,0));
      width: 200px;
    }
}

#loading2 {
    animation-name:             changing2;
    animation-duration:         4s;
    animation-direction:        alternate;
    animation-iteration-count:  infinite;
}

@keyframes changing2 {
    0% {
        fill: var(---loading2-fill-from, rgb(105,105,105));
        width: 20px;
    }
    100% {
        fill: var(--loading2-fill-to, rgb(13,255,191));
        width: 200px;
    }
}
<form>
  <fieldset>
    <legend>#loading</legend>
    <label>
      Loading button fill from:
      <input type="color" id="loading-fill-from" value="#005f73"/>
    </label>
    <label>
      Loading button fill to:
      <input type="color" id="loading-fill-to" value="#94d2bd" />
    </label>
  </fieldset>
  <fieldset>
    <legend>#loading2</legend>
    <label>
      Loading2 button fill from:
      <input type="color" id="loading2-fill-from" value="#f07167" />
    </label>
    <label>
      Loading2 button fill to:
      <input type="color" id="loading2-fill-to" value="#fed9b7" />
    </label>
  </fieldset>
  <button type="button" id="btn">Change color</button>
</form>

<svg id="loading" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" /></svg>

<svg id="loading2" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" /></svg>

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

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

What are the best ways to create a responsive login form?

After recently beginning to learn HTML and CSS, I have encountered some confusion. Take a look at this table design for screens under 500px, and then compare it to how it should appear on screens 500px or larger. I believe utilizing a media query may be t ...

Typescript: Streamline the process of assigning types to enum-like objects

One common practice in JavaScript is using objects as pseudo-enums: const application = { ELECTRIC: {propA: true, propB: 11, propC: "eee"}, HYDRAULIC: {propA: false, propB: 59, propC: "hhh"}, PNEUMATIC: {propA: true, propB: ...

Check the @versionColumn value for validation prior to the entity save operation in TypeORM

I am currently in the process of saving data in a PostgreSQL database using TypeORM with NestJS integration. The data I am saving includes a version property, which is managed using TypeORM's @VersionColumn feature. This feature increments a number ea ...

Unable to see text scrolling in the div container

I am trying to manipulate a div that contains some phrases: <div class="container"> <div class="phrase-doc">Lorem ipsum bla bla</div> <div class="phrase-doc">Lorem ipsum bla bla</div> <di ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Styling a div element in CSS with absolute positioning and the ability to

I am looking to set specific positions and dimensions for the div elements within my HTML document. Refer to this image for reference: https://i.stack.imgur.com/ANBVm.png For each of these div elements, I want a vertical scrollbar to appear if the content ...

Include html into typescript using webpack

Attempting to include HTML content into a variable using TypeScript and webpack has been my challenge. This is the current setup: package.json: { "devDependencies": { "awesome-typescript-loader": "^3.2.3", "html-loader": "^0.5.1", "ts-load ...

Using Pan Responder with Animated.View triggers a re-render for each individual pixel within a React Native application

I have successfully implemented a pan gesture in UITableViewCell, but I am facing an issue where the shouldUpdateComponent function is being called for every pixel of movement, even though I store the translateX property as a class variable. class Threa ...

What could be causing my function to execute thrice?

I cannot seem to figure out why my tag cloud is causing the required function to run multiple times instead of just once when I click on a tag. This issue persists whether using jQuery or plain JavaScript. What am I missing? The code I have is very simple, ...

Is there a way to display list items in rows of three?

I just bought this theme and I'm looking to customize it so that only three items appear in a row on the homepage instead of four. Can this be achieved with CSS or JQuery? Here is the link to the theme: Here is the link Is it possible to use CSS to c ...

Adjust the width of a class using CSS transitions when hovering

Is there a way to use pure CSS to adjust the widths of classes on hover? Although the transition is successfully changing the classes, class .b and .c are not impacting the width of classes that come before them. Ideally, I would like the previous class ( ...

Using Jasmine to Jest: Mocking Nested function calls

I am currently working on testing my TypeScript functions with Jasmine: //AB.ts export async function A() { } export async function B() { A(); } My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I h ...

Customized placement of form fields on an HTML grid determined by the user

My goal is to organize input elements on a grid based on user preferences. After researching, I stumbled upon CSS grids, which seem promising. I am considering creating a CSS grid with r rows and c columns, then using JavaScript to assign input elements t ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

Capacitor and Angular: Trouble with appStateChange listener functionality

In my quest to solve a KPI, I am attempting to trigger a logEvent using the Firebase SDK when the user closes the application (specifically in an Ionic/Capacitor/Angular environment). However, I am facing numerous challenges trying to access the appStateCh ...

Tips for styling an image and vCard within a Foundation accordion menu

I am working on a project that involves creating a list using an accordion feature to display names of individuals. When a user clicks on a person, I want the dropdown content to show their image and vcard details. How can I structure the content so that ...

Tips for aligning a cluster of floating buttons at the center in Vuetify:

This is the code I am currently working with: <v-container height="0"> <v-row align="center" justify="center"> <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" ...

How can you modify the Bootstrap width to activate the responsive design?

I currently have the following HTML code snippet: <!DOCTYPE html> <html lang="en> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale= ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...