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

1

5 Answers 5

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"

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

0

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

1
  • This is a simple way...but go for attributes for programing perspective :) Commented Feb 4, 2011 at 17:31
0

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

0

Framework agnostic script:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.