How to Dynamically Change CSS Style Attribute of Div Tag

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

Changing element style attribute dynamically using JavaScript

It's almost correct.

Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.

However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.

There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...

Is there a way to dynamically change css attributes without defined amount of possible changes

You can use CSS Custom Properties which you can define on the :root, or on any element. When used the element that uses the var will traverse up the DOM using the first variable that matches the one used. These then can be used on any element in your component.

// Place this method in an angular service
function changeColor(color) {
const root = document.documentElement;

root.style.setProperty('--background', color);
}
:root {
--background: red;
}

div {
--background: red;
}

body {
background-color: var(--background);
}

span {
background-color: var(--background);
}

/* You can also utilize the vars in components as well */
/* The below is an example of a component, it doesn't work on stackoverflow though */
:host {
my-component {
background-color: var(--background);
}
}
<button onclick="changeColor('red')">Red</button>
<button onclick="changeColor('green')">Green</button>
<button onclick="changeColor('blue')">Blue</button>
<button onclick="changeColor('#800080')">Purple</button>

<!-- Note here how the same var is also defined on the div -->
<!-- This var will be used on the span instead of the one defined in the root -->
<div>
<span>
Hello World
</span>
</div>

How to dynamically change css styling for a div according to browser screen size

Try reading about and using media queries.

Your code should be something like:

.main {
margin-left: 500px;
}

/* For mobile screens */
@media screen and (max-width: 480px) {
.main {
margin-left: 0;
}
}

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

Apply CSS style attribute dynamically in Angular JS

ngStyle directive allows you to set CSS style on an HTML element dynamically.

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

ng-style="{color: myColor}"

Your code will be:

<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>

If you want to use scope variables:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Here an example on fiddle that use ngStyle, and below the code with the running snippet:

angular.module('myApp', []).controller('MyCtrl', function($scope) {  $scope.items = [{      name: 'Misko',      title: 'Angular creator'    }, {      name: 'Igor',      title: 'Meetup master'    }, {      name: 'Vojta',      title: 'All-around superhero'    }
];});
.pending-delete {  background-color: pink}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">
<input type="text" ng-model="myColor" placeholder="enter a color name">
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}"> name: {{item.name}}, {{item.title}} <input type="checkbox" ng-model="item.checked" /> <span ng-show="item.checked"/><span>(will be deleted)</span> </div> <p> <div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div></div>

Applying CSS style to dynamically created DIV

DEMO FIDDLE

You should use the className property:

divTag.className = "divdrag";

The div now has the appropriate class name and you just need to add all of your styling to that CSS class.

More info here

How to dynamically change CSS class of an HTML tag?

You can add a CSS class based on id dynamically using classList API as follows:

document.getElementById('idOfElement').classList.add('newClassName');

Or the old way:

document.getElementById('idOfElement').className = 'newClassName';
// += to keep existing classes

Alternatively you can use other DOM query methods shown below to find elements. The last three return a collection so you'll have to iterate over it and apply the class to each element in the collection (similar to the example given below each).

  • querySelector

  • querySelectorAll

    elements.forEach(element => element.classList.add('newClassName'));
  • getElementsByClassName

    Array.from(elements).forEach(element => element.classList.add('newName'));
  • getElementsByTagName

    Array.from(elements).forEach(element => element.classList.add('newName'));

In your case

var element = document.getElementById('div1');
if(boolVal)
element.className= 'blueClass'; // += ' blueClass'; to keep existing classes
else
element.className= 'redClass';


Related Topics



Leave a reply



Submit