Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript DOM style.backgroundColor not working properly

My problem is as it follows:

I have a piece of JavaScript code which generates a "new" document using document.write and at first I write the entire heading of the web page. In that head I have a bit of CSS code which looks like this:

<style type='text/css'> 
.black {background-color: black;} 
.white {background-color: #ffffff;} 
td {width:50px; height:50px;} 
</style>

And JavaScript draws a table in the body section. Writing code is basically two for loops which draw a chess board. But that doesn't even matter. Every td element gets a class black or white by which it gets properly coloured. And every td gets a onclick='changeBg(this)' attribute.

Here is where the problem comes to life. I can not access the background color of the element that gets clicked. Function looks like so:

function changeBg(element)
{
    alert(element.style.backgroundColor);
    element.style.backgroundColor = "red";
}

At first I alert the color of the current element. It always alerts a blank notification. After I change the color to red and click on the element again it alerts red. The td's are coloured in the browser and if I inspect them with firebug the have background-color: black | white;

What am I missing and how to fix this? I have realised that if I set td color when creating them using style="color: black | white"; it works but then I don't know to which class they belong.

like image 603
Majster Avatar asked Jan 04 '13 08:01

Majster


1 Answers

You can get the currently applied style using window.getComputedStyle - Docs

function changeBg(element) {
    alert(window.getComputedStyle(element).backgroundColor);
    element.style.backgroundColor = "red";
}
like image 128
techfoobar Avatar answered Sep 18 '22 13:09

techfoobar