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
5 Answers
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
-
This is a simple way...but go for attributes for programing perspective :)Chirag Tayal– Chirag Tayal02/04/2011 17:31:10Commented Feb 4, 2011 at 17:31
If you don't mind using a framework, have a look at jQuery, especially this: http://api.jquery.com/css/