0

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

Skizit
  • 43,506
  • 91
  • 209
  • 269
  • 3
    Duplicate: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – Mikhail Feb 04 '11 at 17:28

5 Answers5

3

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"

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

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

TheBuzzSaw
  • 8,648
  • 5
  • 39
  • 58
0

load new image with black color on click event of the button

Chirag Tayal
  • 459
  • 1
  • 6
  • 14
0

If you don't mind using a framework, have a look at jQuery, especially this: http://api.jquery.com/css/

o1iver
  • 1,805
  • 2
  • 17
  • 23
0

Framework agnostic script:

http://jsfiddle.net/chprpipr/kWRRN/1/

chprpipr
  • 2,039
  • 16
  • 17