1

I have been trying to change the background color of an element on a click event.. But the code seems not to be working..

Html

<td  class="white" onclick="place(this,1,2)"></td>

Style

<style>
        .black{
            width: 70px;
            height: 70px;
            background-color:black;
        }
        .white{
            width: 70px;
            height: 70px;
            background-color:white;

        }
    </style>

Below is a javascript function used..

function place(domObj,row,col){

            alert(domObj.style.backgroundColor);


        }

alert returns null..

surendhar_s
  • 824
  • 2
  • 12
  • 20

2 Answers2

2

The domObj.style only returns styles that are set inline using the style attribute.

For styles that come from a CSS file you need to use something like: window.getComputedStyle

Example from documentation:

var elem = document.getElementById("elem-container"); // this is your domObj
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");

Description:

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.

For your case your function should look like this:

function place(domObj,row,col){

    alert(window.getComputedStyle(domObj,null).getPropertyValue("background-color"));

}

Update

Since Internet Explorer 7, colors are always returned in RGB values. There is not way to return it directly, but you can convert it from RGB to hex with this snippet:

    bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);

where bg is the RGB background string.

Andrei
  • 3,086
  • 2
  • 19
  • 24
  • I am getting the output in rgb(0,0,0)..is there anyway that we could get it as a string just like the one we set..? – surendhar_s May 22 '14 at 07:12
  • @surendhar_s no easy way, you may have to use some kind of mapper between `rgb` and the possible color keyword, also you can try using `cssRule` to get the property, not sure about that ***however*** cssRule will help you get the property in just that rule, other rules may override it, hence `getComputedStyle` is still a different thing. – King King May 22 '14 at 07:16
  • he does not mean the hex string of color, he means the color keyword like `black`, `white`, ... – King King May 22 '14 at 07:16
0

You can play with the className property of element.

your javascript code will be something like this

function place(ctrl)
{
    ctrl.className =(ctrl.className=="white"?"black":"white");
}

See the fiddle here

Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35