change inline class Style property using javascript/jquery - javascript

How to change inline class Style property using javascript/jquery.
for example:
<style>
.iexp-info-bar-body {
background-color: #000000;
}
</style>
<div class="iexp-info-bar-body">
//data
</div>
i want to change background-color property of a class .iexp-info-bar-body #000000 to #C04848 .
Please not that i know inline css technique/using !important keyword to change color.
But i want to change all the occurance of a class .iexp-info-bar-body property
ie
i need a result like
<style>
.iexp-info-bar-body {
background-color: #C04848;
}
</style>
<div class="iexp-info-bar-body">
//data

I had a very good teacher that taught us to change the class :
First, it really helps to be fully aware of "what is my initial state" AND "what is my final state"
This is pretty useful if your design change and you have to implement some transitions. And you will never have to access your JavaScript files to change any css code.
Then think about conflicts
Today, you only have one element depending on that class, but what if you have 100 000 tomorrow ?
Maybe try to make another class is the simplest way to achieve what you want to do.
<style>
.iexp-info-bar-body {
background-color: #000000;
}
.changed {
background-color: #ff69b4;
}
</style>
<div class="iexp-info-bar-body">
//data
</div>
<script>
var all = document.querySelectorAll('.iexp-info-bar-body');
for (var i = 0, length = all.length; i < length; i++) {
all[i].classList.remove('iexp-info-bar-body');
all[i].classList.add('changed');
}
</script>
Of course this is very primitive and you can improve it in many ways

Have a look at a library called jss. Added or modifying classes is as simple as
jss.set('.demo', {
'font-size': '15px',
'color': 'red'
});
This uses the style technique in the header to define the classes similar to the second code block in your question.

Related

How to dynamically change css values (like color in whole app) etc

I have one question...
If you want conditional styling: you must use ng-class or ng-style construction.
But...
For example: I'm an admin, and I want to change color of my application with custom color from colorpicker. How can I change some code in css?
For example I have this line in style.css:
body{
background: #ffffff;
}
(also all tags like a, h1 etc implement some color)
and in controller I change this #ffffff to #000000.
What is the best way to change this color in css, without using ng-class or ng-style on each tag in each controller?
The best way is generate a file like color.css with all css rules with color, background-color, border-color etc. overridden. But angularjs will not be enough.
color-default.css
body {
background: #fff;
}
color.css
body {
background: #f00;
}
Full JS way
Add class on every element you want to override.
Create class for every properties like so:
.skin-color { color: {{color}}; }
.skin-background-color { background-color: {{color}}; }
.skin-border-color { border-color: {{color}}; }
etc..
Apply class on your html where you want:
<h1 class="skin-color">My title</h1>
<p>Hello I'm online!</p>
<p class="skin-background-color">No difference!</p>
<p>I'm link</p>
You can save the color variable in localStorage for example.
Démo: http://codepen.io/anon/pen/jPrabY
You could write the CSS rule in JavaScript and add it to a stylesheet dynamically. A couple of good articles on how to do that are here and here.
var myColor = '#FF00FF';
var stylesheet = /* get stylesheet element */;
stylesheet.insertRule('.dynamic-color { background-color:"' + myColor +'";}',0);
Of course, in a pure Angular way, you would create a directive that wraps the DOM/stylesheet interaction.
The easiest way I can think about is, for example, clicking on myBox changes its background-color.
html:
<div class="myBox" ng-click="changeBackgroundColor()"></div>
js:
$scope.changeBackgroundColor = function(){
angular.element('.myBox').css('background-color', '#000');
}
css:
.myBox{background-color: #fff;}
Hope I've been helpfull.
Another alternative is SASS or LESS and deal with colors using variable...

Changing the class of a div

<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
background-color:red;
}
.green {
background-color:green;
}
</style>
</head>
<body>
<div id="sample" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').addClass("green");
}, 2000);
</script>
<html>
I want to change the background color of the div with id="sample" from red to green in 2 seconds.I added the javasript to add a class with a green background to the div after 2 seconds.But the added class fails to replace the background color of the div element.So is there any solution which can be applied here to change the background color in two seconds.Also i know it is possible,if we add an another class to toggle between the background colors.An another solution will be appreciated.
It's fails because the weight of ID more than the weight of CLASS:
id = 100
class, pseudo-class = 10
element, pseudo-element = 1
You can use id with class:
<body>
<div id="sample" class="red"></div>
</body>
And then toggle from red to green. No need to use !important.
Moreover, if you want to change it with animation, you can use jQuery animate backgroundColor
<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
/*Remove this from here*/
/*background-color:red;*/
}
.green{
background-color:green;
}
.red{
/*Create a class for red alone*/
background-color:red;
}
</style>
</head>
<body>
<div id="sample" class="red" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
// Calling removeClass with no parameters will remove all of the items's classes.
$('#sample').removeClass();
// Now add the class of green
$('#sample').addClass("green");
}, 2000);
</script>
<html>
Cause
The problem is that an id-style is more important (has more 'weight') than a class style, so #sample has higher precedence than .green and the div remains red. There are many rules that dictate which CSS rules have precedence over others. Make sure to read about CSS rule Precedence, so whichever solution you choose, you know why you chose it and what are the consequences.
Fix
There are many ways to fix this, but they all boil down to making sure that the green rule overrules (is equally or more important than) the default red rule.
Solution (Best): Style on classes, not on IDs.
Add a class to the div that indicates what kind of box it is:
<div id="sample" class="samplecontainer"></div>
Now, in the CSS you can easily apply a default style to such elements, and overrule them too:
.samplecontainer {
background-color: red;
}
.samplecontainer.valid,
/* Or just */
.valid
{
background-color: green;
}
Now the CSS doesn't rely on specific elements, but on element definitions. You can say that containers are by default red, and are made green when they become 'valid' (whatever that may mean in this example). This way, you don't rely on ids in the CSS, which prevents very bulky CSS and the undesirable overrule you bumped into.
Note I renamed 'green' to 'valid' to make it more semantic. What if you want to change the border too, or make them blue instead of green? Then you would still need to dig into the JavaScript code, and also change the class names in CSS and possibly fixed style names in HTML and PHP. Or you can just leave the class name 'green' for the blue element, which is very confusing too. So a name describing the type or state (like valid, active, or whatever suits you best) is easier to read and to maintain.
Solution (Sub-optimal): Add Id to the green rule too
Try do change the css like this, so indicate that an element that has id 'sample' and class 'valid' should be green. I think this is quick fix and less optimal compared to the previous one, and your CSS may become bulky if you have many elements that can become green.
#sample.valid{
background-color: green;
}
Solution (Poor): Adding inline style though JavaScript
Instead of adding a class through JavaScript, you can also add inline style. Inline styles (the style attribute), has higher precedence, so adding style="background-color: green" will overrule the color defined in CSS.
$('#sample').css('background-color', 'green');
I wouldn't much prefer this method, since you would have to dig in your JavaScript to change the styling, end it will get really clunkcy when you want to change other properties as well. Each of the solutions above are preferable over this one.
Solution (Poor and risky): Add !important
From CSSTricks: When Using !important is The Right Choice
The unfortunate typical use case goes like this:
WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG
(use !important rule)
OK, now it's working
Then the next guy comes along and tries to
make new changes. He tries to alter some existing CSS rules, but now
his changes aren't behaving how they should....
There are some cases when !important might be the right choice, but it should never be the quick fix for a problem like this, because in the end you'll and up with a CSS that is very hard to maintain, and various !importants will bite each other. Only use it when you have really thought it through.
Change CSS to
.green{
background-color:green !important;
}
DEMO
Please try this one and remove #simple style css
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').css({'background-color':'green'});
}, 2000);
</script>
in the JavaScript you can use just like that
you may find demo
var a;
function function_name() {
a = 1;
setInterval(new_function, 1000);
}
function new_function() {
if (a === 1) {
color = "requred_color";
a = 2;
} else {
color = "another_color";
a = 1;
}
document.body.style.background = color;
}
.green{
background-color:green !important;
}
change your green class like following
.green{
background-color:green !important;
}
Or try
$('#sample').css({background-color:"green"});

How to find all css classes and its css attributes inside a certain div?

i would like to find all classes and ids inside a certain div ! and these css attributes!
Example :
<div class="demo">
<div class="new_class">
<p id="para">This is Demo Paragraph</p>
<a style="background:#ccc">HyperLink</a>
</div>
</div>
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
</style>
Now The question is that: i would like to find all classes and ids which are used inside demo class ! and Their css values too(which style applying now. ).
I would like to find result as below :
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
a{background:#ccc;}
</style>
OP, not sure what your purpose is, but in general, this can be useful. I had a project where I needed to embed a fancy template from one site onto a page on a different site with a very different, and conflicting stylesheet. I used some code similar to the following to grab every applied style from the original content, via document.styleSheets, then reapplied them all as inline styles, so I could put it onto the "parent" site without the stylesheets conflicting.
Fiddle
JS
var selector,rule;
var result=[];
var sheets = document.styleSheets;
for (var i in sheets) {
//rules or cssRules, depending on the browser
var rules = sheets[i].rules || sheets[i].cssRules;
//iterate over every css rule in the document
for (var r in rules)
{
selector=rules[r].selectorText;
rule=rules[r].cssText;
//select demo itself, as well as all of its children
$('.demo, .demo *').each(function () {
//console.log($(this),selector);
//for each element, see if it matches the current rule. add if it does
if ($(this).is(selector))
{
result.push(rule);
}
});
}
}
console.log(result);
//result[0] .demo { height: 100px; width: 100px; background: none repeat scroll 0% 0% rgb(255, 255, 0); }
//result[1] .new_class { height: 40px; width: 40px; background: none repeat scroll 0% 0% rgb(153, 153, 153); }
//result[2] #para { color: rgb(225, 225, 225); }
Granted, you will have to tweak this on your own to do things like, removing duplicate styles that would occur if you were to apply this to a larger block of HTML, and for dealing with inline styles (which this does not attempt to do, but you can get them from the style attribute and work from there...), and possibly the computed style, which you can get with getComputedStyle, as indicated by the #Derek's answer. but this should get you started.
To find all existing id, try:
var ids = [];
$(".demo *").each(function(){ this.id && ids.push(this.id); });
console.log(ids);
Do the same thing for class or anything else.
However, to get your expected output, you must first acquire the defined CSS style for each element. Which one should be included? p by default gets margins and paddings. Do you include those too? You will also need to dig into all the CSS declarations just to find the style that are applied, which is almost impossible to do.
For example,
<div class="yellow"></div>
<style>
div.yellow:not(.blue){
background: yellow;
}
</style>
How do you get the background of the <div> tag? .style.background? Nah, it returns "". Well now you will have to reach into the CSS declaration with document.styleSheets to see which one applied. How do you even check if the rule div.yellow:not(.blue) matches your element? Good luck doing that. (There might be libraries that does this kind of thing, or maybe you can even utilize jQuery's internal selector engine with .is, though it will not be the same as in CSS) Another thing you can do is try getComputedStyle. It gives you every single computed styles that aren't even in your declaration. So what you are trying to do is not possible to do. (I don't even know what you are doing something like this.)

Grouping changes of different element's styles

Is it possible in Javascript to set different element's styles at once, in such way that only one reflow is triggered? For example, is it possible to set at once the color style for different elements as in the below code snippet, in a way that just one reflow is triggered instead of three reflows?
document.getElementById("elem1").style.color = '#000';
document.getElementById("elem2").style.color = '#fff';
document.getElementById("elem3").style.color = '#abc';
I am familiar with techniques (as explained here) that minimize reflows/repaints such as using document fragments or using css classes instead of manipulating css styles through javascript, but I don't see how they can be applied on this case.
EDIT: the three elements on the example are siblings but there might exist, or not, other sibling elements between them, meaning that we cannot assume that they are defined necessarily by that order in the html structure. For example, its possible that we have a structure like this:
<div id="parent">
<div id="elem1">elem1</div>
<div id="elem2">elem2</div>
<div id="elem4">elem4</div>
<div id="elem3">elem3</div>
</div>
Much appreciated for any help!
Cheers
As far as I am aware the is no way to set the class of multiple elements at once. However, the browser may actually batch these changes for you anyway. Providing you don't read styles as well as writing them I believe this should hold true.
This article provides some insight into how reflow and repaint are triggered http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
You can prepare class like this :
.color1{
color : #000;
}
.color2{
color : #abc;
}
And set to your elements like this :
document.getElementById("elem1").className = document.getElementById("elem1").className + " color1";
document.getElementById("elem2").className = document.getElementById("elem2").className + " color2";
Depending on your element structure. For example assuming those elements are sibling DIVs, you can define CSS as:
div.myclass {
color:#000
}
div.myclass + div {
color:#fff
}
div.myclass + div + div {
color:#abc
}
Then a single JS command:
document.getElementById("elem1").className = "myclass";
Would set color for all 3: http://jsfiddle.net/PjZ77/1/
If it makes sense in your case, use css classes and swap the container class.
HTML structure could be :
<div id="container1">
<div id="elem1" class="clsA">A</div>
<div id="elem2" class="clsB">B</div>
<div id="elem3" class="clsC">C</div>
</div>
and in CSS:
#container1 .clsA { color: #000; }
#container1 .clsB { color: #111; }
#container1 .clsC { color: #222; }
#container1.mystate .clsA { color: #DDD; }
#container1.mystate .clsB { color: #EEE; }
#container1.mystate .clsC { color: #FFF; }
You can set document.getElementById("container1").className with mystate class (or empty class, or any class name that makes sense you defined in the css.
Class change occurs for only one element (the container), so the elem(n) child items will be refreshed at the same moment.

Can I prevent a CSS style to be overwritten?

I'd like to apply a CSS to some linkbuttons on page load but one of them <a id="lb1">logoff</a> must keep its style, no hover nor other event must change its style.
The linkbuttons have no class and the css applied to all of them is done to tags, this way:
a
{
//style
}
a:hover
{
// style
}
Is it possible?
No, you can't.
You can use more specific selectors (or even inline CSS with the style attribute) so that they are less likely to be overridden accidentally.
You can use the (eugh) sledgehammer of !important so they will only be overridden by another !important rule.
There is no way to prevent them being overridden though.
Please please please please please avoid using !important whenever possible. You will run into SO many annoying problems and issues from using this. I consider it a very lazy hack.
What you want to do is append a class to the link that you don't want overwritten. Classes are given a higher priority than general selectors (such a, p, b). So if you append this class to the link, the CSS will override the default CSS you have set for a.
CSS:
a {
color: red;
}
a:hover {
color: blue;
}
.derp:hover { /*you can add everything you want to preserve here, essentially make it the same as the link css. you can also change it to #lbl:hover, although there's no good reason to be using an ID as a CSS selector*/
color: red;
}
HTML:
this will turn blue on hover
<a class="derp" href="#">this will stay red on hover</a>
Here's a fiddle to show you. The second link has a class appended that preserves the original style: http://jsfiddle.net/p6QWq/
Why not add a class to all the link buttons you want to change, and not add it to the one you don't want to change.
Then you can call:
$(".myClass").css("backgound-color", "blue");
This would change the background color for every element with a class of myClass to a blue background.
Or you could add a whole new class to the link buttons that have a class of myClass:
$(".myClass").addClass("myExtraClass");
This would then make the class attribute of your link button class="myclass myExtraClass"
Seeing your code posted makes it a little more clear on what you want to do. Try this:
a {
text-decoration: none;
color: orange;
}
a:hover {
text-decoration: underline;
color: blue;
}
This would apply a default style to all <a> elements. Now you could overwrite this default style by providing a specific style for the anchor with the id you gave above:
#lb1 {
color: black;
text-decoration: none;
}
#lb1:hover {
color: black;
text-decoration: none;
}
I mocked this up in a quick and dirty jsFiddle. See if this gives you the desired result. IDs take precedence over classes and default element styling. So if you have one that you want to keep the same, apply and ID and style the particular element accordingly. This would also help you by preventing you from having to apply a class to several elements. It's less coding to apply one ID than to apply twelve classes. (Just an exaggerated example. I don't know how many links you have.)
Hope this helps.
css is cascading by definition, so any style you apply to a tags will apply to this specific one, except if you overwrite it.
You'll have to either assign a class to all the other buttons or overwrite all the default properties for this specific button.
Also, do not forget the pseudo-classes :visited and :active.
You should use !important in your css like :
a {
/* style */
background: #FFF !important;
}
a:hover {
/* style */
background: #FFF !important;
}
You could always overwrite your css by simply creating another stylesheet and place it at the END of your stylesheet links in the head of your html.
<head>
<link rel="stylesheet" href="location/location/first_stylesheet.css">
<link rel="stylesheet" href="location/location/revised_stylesheet.css">
</head>
This is not the most productive method of overwriting your css however; one would be well advised to eliminate the necessity for this separate stylesheet by simply appending elements with a class attribute. The class attr will allow you to modify basic html elements, tags and overlay a final layer to "rule them all". Enjoy!

Categories

Resources