I'm wondering how would I change a CSS element in javascript..e.g if a user clicks a button it changed the background from white to black
Every DOM element has a style property that allows manipulation of CSS properties on that object as if you were mucking with it's style attribute.
The below will toggle the color of the document body but is equally applicable to other HTML elements.
<button onclick="document.body.style.background = (toggle = !toggle) ? 'black' : 'white'">Toggle Background</button>
As TheBuzzSaw points out, you need to camel case them.
So the JS property is backgroundColor instead of background-color.
The rule is basically
var javascriptProperty = cssStyleProperty.replace(
/-([a-z])/g,
function (_, followingLetter) { return followingLetter.toUpperCase(); });
but there are a few exceptions : since float is a keyword in many languages, the CSS style property is cssFloat. The exceptions are explained under JavaScript syntax in the w3schools pages : http://www.w3schools.com/css/pr_class_float.asp
JavaScript syntax: object.style.cssFloat="left"
There are many properties/attributes that can be manipulated directly from JavaScript. You just need to know their names. They are usually strange camel case equivalents of the CSS property names. A quick Google search reveals lots of places to learn about this.
http://www.comptechdoc.org/independent/web/cgi/javamanual/javastyle.html
load new image with black color on click event of the button
If you don't mind using a framework, have a look at jQuery, especially this:
http://api.jquery.com/css/
Framework agnostic script:
http://jsfiddle.net/chprpipr/kWRRN/1/
Related
I have an HTML page containing XML. Using Javascript, the XML attributes can be changed when the user clicks a button. (So far, everything works)
However, the attribute that is changed is used in the linked CSS to determine the background color of the element. When the attribute value is changed, the style is not refreshed, so the color doesn't change.
I can alter the javascript to also change the color, but that would involve hardcoding the color, and partially defeat the point of using CSS.
So, it seems to me, I need to do one of two things, and I can't figure out how to do either:
read the color from the CSS, and then assign it using javascript
somehow use javascript to have the CSS re-applied to the document.
Which approach is better? I assume the 2nd is easier, unless there is a side-effect I haven't thought of. And, whichever approach is better, HOW TO DO IT?
My CSS contains:
*[cleared=true] {
background:lightgrey;
}
My XML looks like this:
<Transfer ID="31266" Date="2015-04-14" Cleared="false">
<AccountCharge Account="Unplus">-826.20</AccountCharge>
<AccountCharge Account="Amex">826.20</AccountCharge>
<TransactionID>1504140662984782</TransactionID>
</Transfer>
My Javascript is:
function Reconcile(Element_ID){
try {
var c=document.getElementById(Element_ID);
c.setAttribute('Cleared','True');
}
catch(e) {
alert(e.description);
}
}
I have tried changing the script from modifying 'Cleared' to 'Date', and I can see the date change. The 'Cleared' attribute is not displayed directly by the CSS, but is used to set the formatting of other elements and/or attributes.
Changing the value of 'Cleared' before the page is loaded has the effect I expect - the CSS causes the formatting I expect. However, after the page is loaded, when the javascript changes the value of 'Cleared', no visible change in formatting takes place.
Did you try to assign classes?
Either with pure Javascript:
document.getElementById('selector').className = 'active';
or with jQuery:
jQuery('#selector').addClass('active');
This way you can use CSS classes and not hardcode the colour in your Javascript code.
See implementation of addClass and removeClass in Javascript:
http://jaketrent.com/post/addremove-classes-raw-javascript/
There's some info about changing style of HTML element with jQuery: jQuery changing style of HTML element
There's some more if you change your mind: How to modify STYLE attribute of element with known ID using JQuery
You can either add some extra styles or just switch the target class/id.
here is my code
<!doctype html>
<html>
<head>
<style>
body {
color:red;
}
</style>
<script>
window.onclick = function(){
document.getElementsByTagName("body").color="blue";
}
</script>
</head>
<body>
here is some text for test
</body>
when i run it in my browser (initially it is red) and click in window it doesn't respond to click i mean it should change the color of text from red to blue but nothing happens. Where am i wrong?
Try this:-
Demo
This will add style attribute to the body element, which will override the css rule.
window.onclick = function(){
document.getElementsByTagName("body")[0].style.color="blue";
}
It should be style.color as color is a property of style property of element and even though it is body .getElementsByTagName returns a collection so you need to use document.getElementsByTagName("body")[0] to get the element and apply style to it.
And yes styles applied the element direclty will override the class css rule
Style property has more precedence over styles applied by class.
document.getElementsByTagName("body").color="blue";
This has more preference
Also color is a property of style attribute.
So your style should have looked something like this as getElementsByTagName returns a node list.
document.getElementsByTagName("body")[0].style.color="blue";
it is a better idea to use classes instead, cause it is lot cleaner.
Inline CSS is more powerful and overrides CSS defined anywhere else.As far as working of your code, I modified it a little bit like this:
window.onclick = function(){
//document.getElementsByTagName("body").color="blue";
document.body.style.color="blue";
}
DEMO here
You have an error in your JS. getElementsByTagName returns a NodeList (which is like an array), not a single element. You need to set the property on an element, not a NodeList. For example:
document.body.color="blue";
Setting the color property of the body element (IIRC, it's been a very long time since I went near that part of HTML) is equivalent to setting the color attribute. This is an obsolete presentational hint attribute.
The CSS specification says:
The UA may choose to honor presentational attributes in an HTML source document. If so, these attributes are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet. They may therefore be overridden by subsequent style sheet rules. In a transition phase, this policy will make it easier for stylistic attributes to coexist with style sheets.
So the style specified in the stylesheet should continue to apply.
On the other hand, setting a style.something property is equivalent to modifying the style attribute on an element.
document.body.style.color="blue";
In the cascade, !important declarations aside, properties set via the style attribute are most specific.
So of those two rules, the blue one would win.
JS inserts the changes inline, giving them pretty much the highest priority, unless you have !important in your css.
Check to see if you code (document.getElementsByTagName("body").color="blue";) works from the dev console (F12 for Chrome). There appears to be a problem with it. I can't help debug, however, as I usually do such actions via jQuery, and vanilla JS color changes are unintuitive for me.
js and css does not compete with each other, what you are doing is essentially javascript applying css to an html element, this means that its still css, that type of css is called inline css, . As others have said inline css has more precendence over normal css except if you use !important in your css rules
As to why your code is not working, because you are doing it wrong.
Change
document.getElementsByTagName("body").color="blue";
To
document.getElementsByTagName("body")[0].style.color = 'blue';
Here's a jsFiddle
http://jsfiddle.net/n2kqd/
What I want to do is $('.class.img').css('cellpadding', variable);
It doesn't seem to be working. I tried googling to no avail. Any help would be appreciated. I'm trying to apply it to an image inside the element with the given class.
CSS applies the styling properties inline as in style="..." and does not modify the .class itself.
$('.class').css does not do anything.
$('.class').css('color','red') writes a color style
$('.class').css('color') reads the color style
So to target your img elements within an element with class "cellBox":
var borderx = "1px solid red";
$('.cellbox img').css('border',borderx);
(That sets border, but you can set padding the same way.)
Check working example at http://jsfiddle.net/SBjfp/2/
(Note that the jQuery documentation says that shorthand properties like padding or border are not supported; this mostly applies to getting the properties; setting [as above] usually works because it's supported by the underlying browser's implementation.)
The jQuery selector engine works perfectly well with class selectors.
The only thing clearly wrong with this (there might be other things, but you haven't provided any context (such as what the document looks like or when the statement is run)) is that css is a function, and you aren't calling it (i.e. css('foo')).
Assume you have a list item, <li id="foo"> which you want to fade from one color to another when moused over, and that you are using jQuery. This is fairly easy:
$('li#foo').bind('mouseenter' , function(e) {
$(this).animate({backgroundColor: '#F00'} , 300);
});
However, what if you wanted to get the resulting color or other style rules from a class defined in CSS without also declaring them in JavaScript? It seems there's no way to learn style information from CSS rules without having an example of the rule already in the document, which would require you to animate the <li> to the target appearance, then in the animation-finished callback, set the class which leads to redundant style declarations and can foul up your CSS at "runtime".
Sorry if this question's unclear: It doesn't occur in the context of any specific project, I'm just curious how you'd go about this. Also, I know CSS3 hypothetically includes support for such transitions but using CSS for dynamic behavior like this seems such an ugly hack.
I'm pretty sure javascript can't read your style-sheet.
If you want a certain property from the style-sheet that does not occur anywhere on the page, you will have to add an invisible element that has that style applied, either at page-load time in the html or with javascript whenever you want.
It does seem a bit theoretical though, instead of defining styles in your style-sheet that you are not using, you might as well declare the appropriate variable directly in javascript.
You need the color plugin to animate background color.
You should be able to simply do:
$(this).css('background-color')
If you want to get the color AFTER its been updated, add it to the callback, like:
$('li#foo').bind('mouseenter' , function(e) {
$(this).animate({backgroundColor: '#F00'} , 300,function(){
alert($(this).css('background-color'));
});
});
You can then save that to a var, or do whatever you wanted to do with it. You could also change your "bind" to "live" and it will update automatically each time its run:
$(selector).live(event,function(){
alert($(this).css('background-color'));
});
As a side note, you shouldnt do li#foo :) just do #foo speeds up your selection time and its unnecessary as there is only 1 element with that ID.
I've played around a little with Calvin's idea, and this is what I got:
Assuming the following CSS:
#somediv .bar em {
color: #080;
}
You can create the elements virtually and get the style information that way:
$('<div id="somediv"><span class="bar"><em>')
.find('em').css('color')
Watch it in action.
I want to do this:
e.className = t;
Where t is the name of a style I have defined in a stylesheet.
If e is a reference to a DOM element and you have a class like this: .t {color:green;} then you want reference the class name as a string:
e.className = 't';
Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the DOM Level 2 Style interface. e.g.,
button.style.fontFamily = "Verdana, Arial, sans-serif";
where button is (presumably) a button object. :-)
Not only that works, but it's even a best practice.
You definitively want to separate the data format (xHTML) from the design (CSS) and the behaviour (javascript).
So it's far better to just add and remove classes in JS according to event while the esthetic concerns are delegated to css styles.
E.G : Coloring an error message in red.
CSS
.error
{
color: red;
}
JS
var error=document.getElementById('error');
error.className='error';
N.B :
This snippet is just an example. In real life you would use js just for that.
document.getElementById is not always interoperable. Better to use a JS framework to handle that. I personally use JQuery.
Here is the example that add and remove the class using jQuery.
// js
$("p:first").addClass("t");
$("p:first").removeClass("t");
// css
.t {
backgound: red
}
document.getElementById('id').className = 't'