How to Dynamically Change the Value of a CSS Property Inside a Stylesheet

How to dynamically change the value of a CSS property inside a stylesheet?

Here you go:

[].every.call( document.styleSheets, function ( sheet ) {
return [].every.call( sheet.cssRules, function ( rule ) {
if ( rule.selectorText === '.myclass' ) {
rule.style.backgroundColor = 'green';
return false;
}
return true;
});
});

Live demo: http://jsfiddle.net/gHXbq/

ES5-shim for IE8

Generate dynamic css based on variables angular

Direct approach available in angular is using ngstyle as follows

<div [ngStyle]="{'color': style.colorVal ? style.colorVal : '#000', 'font-size' : style.fontSize ? style.fontSize : '16px' }"></div>

After going through different methods and approached to add dynamic css to all pages on angular app I ended up with following solutions.

Requirement : generate dynamic css based on values returned from and API to change design and styling.

Solution :

  1. create a new component and create a service to load dynamic css variables from API.
  2. Add style tag in template file and use variable values for properties.
  3. Load this template on all pages or on main template.
  4. On app build style will be moved to head tag.

Code sample

import { CssService} from './Css.service';

@Component({
selector: 'DynamicCss',
templateUrl: './DynamicCss.component.html',
styleUrls: ['./DynamicCss.component.scss']
})
export class ServiceProviderComponent implements OnInit {
cssVariables: any;
constructor(private cssService:CssService){
/* call the service/api to get the css variable values in cssVariables */

}
}

Now apply css using jquery or javascript to append css with help of function like following

appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}

and call this function after loading custom data from service or other variable like I did it ngOnInit

ngOnInit(){
this.appendCss(this.customizeFormData);
}

Its using jquery but can be done with javascript/typescript as well if you dont want to use jquery in your angular app

Other useful resource https://github.com/angular/angular/issues/9343#issuecomment-312035896

How can I dynamically change the value of a CSS property in React?

Directly you can pass to html tag as an object style like this

<div className="background" 
style={{ opacity: this.props.opacity }}
/>

How to dynamically set and modify CSS in JavaScript?

If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...

myElement.style.width = "400px";

...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a whole lot you can do about that. You're trying to set css dynamically, after all.

Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.

How to style dynamically in lit?

You can't use ‍${} in lit css tag function!

But you can select element and then change style

import {html, css, LitElement} from 'lit';
import {customElement, property, query} from 'lit/decorators.js';

@customElement('dynamic-style')
export class DynamicStyle extends LitElement {
static styles = css`
label {
color: #023047;
}
`;

@property()
color: string;

@query('input') input: HTMLSelectElement | undefined;
@query('label') label: HTMLSelectElement | undefined;

render() {
return html`
<label
>Enter HEX color
<input class="color-input" placeholder="#023047" />
</label>
`;
}

firstUpdated() {
this.input.addEventListener('input', () => {
this.label.style.color = this.input.value;
});
}
}

lit playground

Also read:
Dynamic classes and styles | Lit Doc

Use CSS variable in Lit

Simply! It is good to search more and then ask

How to dynamically change the style tag using JavaScript?

You are probably trying to add css to the style tag. This can be accomplished using:

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here

You can also use:

document.styleSheets[0].cssText = ""; //some css goes here

Apply CSS dynamically with JavaScript

Using Jquery

Use the css() function to apply style to existing elements where you pass an object containing styles :

var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);

You can also apply one style at the time with :

$("#myId").css("border-color", "#FFFFFF");

Vanilla JS :

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

With Css :

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

in your css file you can have classes like

.myClass {
background-color: red;
}

.myOtherClass {
background-color: blue;
}

Again using jquery, to add or remove a class to an element, you can use

$("#myDiv").addClass('myClass');

or

$("#myDiv").removeClass('myClass');

Again, you can also do the same with vanilla JS:

document.getElementById("#myId").classList.add('myClass') 

or

document.getElementById("#myId").classList.remove('myClass') 

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.

apply CSS style to particular elements dynamically

Without using classes:

/* using CSS */
div p {
color: #ff0000;
}

// using jQuery
$("div p").css({
color : "#ff0000"
});

With classes for <p> elements:

<!-- HTML -->
<div>
<p class="mypar">...</p>
<p class="mypar">...</p>
</div>

/* using CSS */
div p.mypar {
color: #ff0000;
}

// using jQuery
$("div p.mypar").css({
color : "#ff0000"
});

With classes for <div> element:

<!-- HTML -->
<div class="mydiv">
<p>...</p>
<p>...</p>
</div>

/* using CSS */
div.mydiv p {
color: #ff0000;
}

// using jQuery
$("div.mydiv p").css({
color : "#ff0000"
});


Related Topics



Leave a reply



Submit