Reputation: 130
So this is a very simple application. Essentially, I have my initial background set by CSS. I want to be able to read the current background color in javascript and update it. Currently, my alert in the updateBackground function shows no text at all, despite the fact that my CSS is definitely loaded and there is no race problem due to waiting on deviceReady. I could easily hack around this by setting the backgroundColor in javascript, but I'd like to understand this behavior.
CSS
body{
background-color: green;
}
Javascript
var updateBackground = function() {
alert(document.body.style.backgroundColor);
document.body.style.backgroundColor=document.body.style.backgroundColor == '#E4E4E4' ? 'green' : '#E4E4E4';
};
class App{
constructor() {
this.bindEvents();
}
bindEvents() {
document.addEventListener('deviceready', this.onDeviceReady, false);
}
onDeviceReady(){
document.addEventListener('touchstart', function() {
updateBackground();
}, false);
}
}
var app = new App();
Upvotes: 0
Views: 136
Reputation: 3726
document.body.style.backgroundColor does not read the color set in your css file, only the one you set by style attribute on the element. getComputedStyle(document.body).getPropertyValue("background-color") is what you want.
<html>
<head>
<style>
body{background-color: green}
</style>
<script>
function getStyle(){
alert(getComputedStyle(document.body).getPropertyValue('background-color'))
}
</script>
</head>
<body onload = 'getStyle()'>
</body>
</html>
Upvotes: 1