Reputation: 884
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..
Upvotes: 1
Views: 3359
Reputation: 3735
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
Upvotes: 0
Reputation: 3106
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"));
}
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.
Upvotes: 2