<!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"});
Related
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.
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...
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!
The HTML tag on this page I'm working on is in a class that is giving it a top padding of 28px. I need this to go away temporarily when a button is clicked, but it doesn't appear that I can change the styling of the HTML tag itself.
Will I need to use position: relative; on the body tag or something similar? Is there really a way to assign CSS to the HTML tag that I don't know about?
# Comments:
Sorry, I'm in a bit of a rush here. It's something to the effect of this:
<html class='pad_my_top'>
<head>
<style type='text/css'>
.pad_my_top{
padding-top: 28px;
}
body{
background: #000000;
}
</style>
<script type='text/javascript'>
function its_gone(){
// Something here to remove padding.
alert("It's gone. Hurray!");
// Something to put it back.
}
</script>
</html>
<body>
<button onClick='its_gone()'>Click me to get rid of the top padding</button>
</body>
</html>
I really want it gone so I can print the page with Javascript, but I'd rather not use any 3rd party code because this is for a plugin for Wordpress and I don't want a billion dependencies. I only need to hide/re-display 3 divs and (re)change 2 styles.
Use this to remove the top padding:
document.documentElement.style.paddingTop = "0";
and this to set it back:
document.documentElement.style.paddingTop = "28px";
There's no reason to use getElementsByTagName and whatnot...just use document.documentElement. Also, it's better to use a class and toggle that instead of directly setting the style attribute. What if you change the 28px to 20px in your CSS? Then you have to change it somewhere else. Since you are sure you want the top-padding to be 0, then add a class that sets that. When done, remove that class. Like this:
<style type="text/css">
.no-top-padding {
padding: 0 !important;
}
</style>
document.documentElement.className += " no-top-padding";
And to "add" the padding back (by effectively removing the class):
var old_class = document.documentElement.className;
document.documentElement.className = old_class.replace(/(?:^|\s)no-top-padding(?!\S)/g, "");
Although it could be done a lot cleaner with the DOM API classList. The regex is just a safer way for making sure the className property is modified correctly to remove the "no-top-padding" class.
Guys I want to fix a div width and height as 100%. But the problem is that div is inside a wrapper with a fixed width.
I have a button above the div which onclick="" makes the div to change its class with full width and height. i want to position that div to the top-left corner of the window.My code is
<html>
<head>
<title>Javascript Change CSS Class of Div tag</title>
<style type="text/css">
#wrapper
{
width:75%;
height:75%;
margin:0 auto;
}
.minimize {
color : red;
width:500px;
height:200px;
background:#474747;
float:left;
}
.maximize {
color : blue;
width:100%;
height:100%;
float:left;
background:#ccc;
}
</style>
<script language="javascript" type="text/javascript">
function changeCssClass(navlink)
{
if(document.getElementById(navlink).className=='minimize')
{
document.getElementById(navlink).className = 'maximize';
}
else
{
document.getElementById(navlink).className = 'minimize';
}
}
</script>
</head>
<body> <div id="wrapper">
<div id="navlink" class="minimize"><input type="button" value="click here" onclick="changeCssClass('navlink')" /> </div>
</div>
</body>
</html>
But i want to make it to look like this with wrapper
<html>
<head>
<title>Javascript Change CSS Class of Div tag</title>
<style type="text/css">
.minimize {
color : red;
width:500px;
height:200px;
background:#474747;
float:left;
}
.maximize {
color : blue;
width:100%;
height:100%;
float:left;
background:#ccc;
}
</style>
<script language="javascript" type="text/javascript">
function changeCssClass(navlink)
{
if(document.getElementById(navlink).className=='minimize')
{
document.getElementById(navlink).className = 'maximize';
}
else
{
document.getElementById(navlink).className = 'minimize';
}
}
</script>
</head>
<body>
<div id="navlink" class="minimize"><input type="button" value="click here" onclick="changeCssClass('navlink')" /> </div>
</body>
</html>
Will any one help here....
If anyone has any suggestion??
I think this is what you were after, but it was hard to tell because you didn't specify exactly what states should be held for .minimize and .maximize.
Notice that the javascript is substantially different than your original.
Since 'class' is an attribute on DOM elements, it should be accessed using getAttribute and setAttribute. There was a very, very old bug in IE6 that would only let javascript access an element's classes via className, but that is no longer the case.
Additionally, take notice of how I'm handling the class attribute. Since you can specify multiple classes on an element, this code takes that into account. You can safely add more classes without fidgeting with maximize and minimize.
The 2nd thing to look at is the css. Using position:fixed will lock the element into position no matter what the scroll value is. In this example, there are 2 ways to set the div to be full screen. The first is specifying width and height at 100%. However, this is brittle.
Its better to set top, right, bottom, and left to 0. This gives you more control. Also, suppose you wanted a thin margin around the edges. Instead of worrying about mixing top and left with width and height, you can just specify a pixel or percentage value for the 4 properties I've mentioned to get an easy, uniform look.
I checked Berker's fiddle and it will fix your problem.
Sowmya uses this fiddle, but I have made a few changes, check this out:
Since class is an attribute on DOM elements, it should be accessed using getAttribute and setAttribute. There was a very, very old bug in IE6 that would only let javascript access an element's classes via className, but that is no longer the case.
Take a look at this fiddle, http://jsfiddle.net/Tv2pP/7/
I think this is what you were after, but it was hard to tell because you didn't specify exactly what states should be held for .minimize and .maximize.
Notice that the javascript is substantially different than your original.
Since 'class' is an attribute on DOM elements, it should be accessed using getAttribute and setAttribute. There was a very, very old bug in IE6 that would only let javascript access an element's classes via className, but that is no longer the case.
Additionally, take notice of how I'm handling the class attribute. Since you can specify multiple classes on an element, this code takes that into account. You can safely add more classes without fidgeting with maximize and minimize.
The 2nd thing to look at is the css. Using position:fixed will lock the element into position no matter what the scroll value is. In this example, there are 2 ways to set the div to be full screen. The first is specifying width and height at 100%. However, this is brittle.
Its better to set top, right, bottom, and left to 0. This gives you more control. Also, suppose you wanted a thin margin around the edges. Instead of worrying about mixing top and left with width and height, you can just specify a pixel or percentage value for the 4 properties I've mentioned to get an easy, uniform look.
Lastly, if you have the option you should use a standardized library like jQuery. It has become an incredibly useful tool over the years for doing exactly this kind of thing without you, the developer, having to worry about the underlying browser platform discrepancies too much.
Remove margin:0 auto from the wrapper class
Check this http://jsfiddle.net/PAj39/
Take a look at this fiddle, http://jsfiddle.net/Tv2pP/7/
I think this is what you were after, but it was hard to tell because you didn't specify exactly what states should be held for .minimize and .maximize.
Remove margin:0 auto from the wrapper class
Check this http://jsfiddle.net/PAj39/
The below method makes the inner div to align top left to the browser
add position:fixed; top:0; left:0 to .minimize
Demo http://jsfiddle.net/PAj39/2/
Just set the div width:100%; with position:fixed; to it.
But the wrapper must have position:absolute; property