Change CSS Dynamically

Dynamically change CSS rules in JavaScript or jQuery

You jQuery .css() method to do that.

$('.red').css('color', 'purple');

For multiple rules:

$('.red').css({
'color': 'purple',
'font-size': '20px'
});

When you add dynamic element in future to DOM by the way of append, just give those element some class or id and write CSS rules like above after appending them and they will applied for all dynamically created element.

Working sample

Note

Add dynamic rules is not a good solution in my point of view. Instead of the you can load some external CSS file.

But if you need something like dynamic rules add method then:

$('head').append(
$('<style/>', {
id: 'mystyle',
html: '.red {color: purple }'
})
);

And for future use:

$('#mystyle').append(' .someother { color: green; font-size: 13px } ');

Working sample

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.

Dynamically change css files

I believe you could achieve this through using html data attributes instead of using separate CSS files if it is a theme change you are going for.

function switchTheme(e) {  let theme = document.getElementById("theme-selector").value;  let app = document.getElementById("app");  app.setAttribute('data-theme', theme);}
[data-theme="1"] {  --foreground-color: #eeeeee;  --background-color: #222222;}
[data-theme="2"] { --foreground-color: #000000; --background-color: #eeeeee;}
h1 { color: var(--foreground-color); background-color: var(--background-color);}
<div id="app" data-theme="1">  <h1>A cool title with different colors...</h1></div>
<select id="theme-selector" onchange="switchTheme()"> <option value="1">Theme 1</option> <option value="2">Theme 2</option></select>

How to dynamically change a class css styling?

A more shorten format:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');

The snippet:

$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');

$("p").addClass("redclass");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>I want to be red! And I am.</p><span>I want to be red too but I'm not :'(</span>

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.

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 to change a property of a CSS class dynamically using javascript (no JQuery)

I don't know what triggers your animation, but let's say it's a click on each of the .sbox elements.

As you can't change the CSS, you can instead use the script to add an inline style height using .style.height.

Here is a snippet:

var sboxes = document.querySelectorAll(".sbox");
sboxes.forEach(function(box, index){ box.onclick = function(){ box.style.height = "360px"; box.className = 'sboxopen'; }})
.sbox {  height: 0px;  transition: height 1s ease-out;  overflow: hidden;  border: 8px solid gray; /* Added for better visibility */}
.sboxopen { height: 130px; transition: height 1s ease-out; overflow: hidden; border: 8px solid gray; /* Added for better visibility */}
<div class='sbox'>Box 1</div><br><div class='sbox'>Box 2</div><br><div class='sbox'>Box 3</div>

How to dynamically change CSS style attribute of DIV tag?

var div = document.getElementById('div1');

// Clear Value
div.setAttribute('style','');
// OR
div.removeAttribute('style');

// Set Style / Append Style
div.style.backgroundColor = '#ff0000';

Don't modify the style attribute directly when adding or changing styles unless you want to remove them all.

JavaScript removeAttribute: https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute
Javascript Style: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

how to change css class dynamically with angular

Try this demo code.

Created a method in ts file as:

  activateClass(tab) {
this.selectedTabName = tab;
}

and in html

    <li *ngFor="let tab of tabs"  (click)="activateClass(tab)" class="nav-item">
<a class="nav-link" id="{{tab}}-tab" [ngStyle]="{'background-color': (selectedTabName === tab) ? 'red' : 'black' }" data-toggle="tab" href="#{{tab}}" role="tab" >{{tab}}</a>
</li>

replace above code of [ngStyle] , with below one to meet your requirement of display:none

[ngStyle]="{'display': (selectedTabName === tab) ? '' : 'none' }"

Not sure how will someone ever select another tab when it in display:none state

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



Related Topics



Leave a reply



Submit