/    Sign up×
Community /Pin to ProfileBookmark

Simple but baffling problem – Javascript cant change CSS div’s background color?

Hi. I have a page.

The relevant elements are:
CSS of the object:

[code]
div.chColor
{
width: 60px;
height: 50px;
padding:0px;
border:2px solid;
border-color: rgb(84, 84, 84);
margin-left: auto;
margin-right: auto;
background-color: rgb(0,0,0);
text-align: center;
opacity: 1;
}
[/code]

HTML code for the object:

[code]
<div class=”chColor” id=”colorthis”><br /></div>
[/code]

Javascript code:

[code]colorTimer = window.setInterval(“colorme()”, 10);
red123 = “255”;
blue123 = “255”;
green123 = “255”;
colorstr = ‘rgb(‘+red123+’,’+blue123+’,’+green123+’);’;
document.write(colorstr);
function colorme() {
if (red123 < 255) {
red123 += 1;
} else {
morphTimer= false;
}
document.getElementById(“colorthis”).style.backgroundColor = “rgb(255,255,255);”;
}
function resetcolor() {
red123 = 0;
blue123 = 0;
green123 = 0;
}[/code]

Notice how the code has been reverted to a very simple state. The only code that is important anymore is the following.

[B] NOTE: Again, the above code has a lot of redundant stuff because I was trying to get something else working. It has, again, been reverted to a simple test state that still won’t work. [/B]

[code]“document.getElementById(“colorthis”).style.backgroundColor = “rgb(255,255,255);”;[/code]

.
It is called every ten milliseconds and it won’t work.

This is the code setup I am trying to get working.

[code]
colorTimer = window.setInterval(“colorme()”, 10);
red123 = “255”;
blue123 = “255”;
green123 = “255”;
colorstr = ‘rgb(‘+red123+’,’+blue123+’,’+green123+’);’;
function colorme() {
if (red123 < 255 && blue123 < 255 && green123 < 255) {
red123 += 1;
blue123 += 1;
green123 +=1;
} else {
morphTimer= false;
}
document.getElementById(“colorthis”).style.backgroundColor = colorstr;
}
function resetcolor() {
red123 = 0;
blue123 = 0;
green123 = 0;
}[/code]

This code is supposed to take a standard pitch black div and make it gradually turn right over time. This was my first attempt, which didn’t work. I eventually reverse engineered it to try to find the problem and found out that the line:

[code]document.getElementById(“colorthis”).style.backgroundColor = colorstr;
[/code]

, a line reliable for changing every other aspect of the div in every other script, does not work. This is definitely the culprit.

However, it doesn’t always refuse to change.

If I use:

[code]document.getElementById(“colorthis”).style.backgroundColor = 255;
[/code]

For some mysterious reason, the box turns blue.

I hope I am making sense. This is driving me nuts. On the same page with very similar codes, I’ve got divs morphing all other the place, divs on top of other divs, divs spinning around all over the page, but I cannot make one div do something as little as change a color.

It’s like going to a five star restaurant and being confused and angry as the waiter tells you “We serve all kinds of stuff unless it has bread on it or involves lettuce. We don’t believe in bread or lettuce.”

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@ScriptageJul 16.2011 — Use background instead of backgroundColor.
Copy linkTweet thisAlerts:
@LeopardsonauthorJul 16.2011 — Thanks for the answer, but that didn't help or change any of the results.
Copy linkTweet thisAlerts:
@toicontienJul 16.2011 — You are not modifying the colorstr variable when setting the background color. You modify the RGB numbers but not that string, so the background color never changes. You'll need to rebuild the colorstr string on each interval.
Copy linkTweet thisAlerts:
@LeopardsonauthorJul 16.2011 — What do you mean? I don't understand.

The Colorstr variable builds a string based on Red which is confirmed to be, in the testing default, "rgb(255,0,0)". The document.getElementById string is supposed to set the value of the background color to the value returned by Colorstr.

What am I doing wrong?
Copy linkTweet thisAlerts:
@toicontienJul 17.2011 — Oh! Sorry. I was looking at the wrong post. Does your interval start before the "colorthis" DIV tag has been parsed into memory, e.g. does the DIV tag appear before your JavaScript in the document? If not, then the DIV tag might not exist in memory yet, so document.getElementById("colorthis") is returning a null value, which will throw an error.
Copy linkTweet thisAlerts:
@LeopardsonauthorJul 17.2011 — The Div appears after the script. Again, when I change the value to '''document.getElementById("colorthis").style.backgroundColor = 255;'' the box turns blue. It is definitely changing the value of the Background Color. Why doesn't it work when I make it "document.getElementById("colorthis").style.backgroundColor = "rgb(255,0,0);" or "document.getElementById("colorthis").style.backgroundColor = colorstr;"? This is what is so confusing.
Copy linkTweet thisAlerts:
@chrisecclesJul 17.2011 — The Div appears after the script. [/QUOTE]

I think toicontien has identified the issue.

Your DOM may not be complete by the time the JS begins execution.

When scripts *sometimes* work and *other times* don't, or when there

are inconsistencies in interpreting parameters to methods (like in your

255 example returning a blue bgColor), it can be down to the random

result of the race between Javascript and the browser rendering.

Don't kick your script in until the page is loaded.

Just my 2¢ worth.

Chris
Copy linkTweet thisAlerts:
@toicontienJul 17.2011 — Looking back at your original code, the colorstr variable is the problem.

[CODE]colorTimer = window.setInterval(colorme, 10);
[B]red123 = 255;
blue123 = 255;
green123 = 255;[/B]

function colorme() {
if (red123 < 255 && blue123 < 255 && green123 < 255) {
red123 += 1;
blue123 += 1;
green123 +=1;
} else {
[B]clearInterval(colorTimer);[/B]
}
[B]document.getElementById("colorthis").style.backgroundColor = 'rgb('+red123+','+blue123+','+green123+');';[/B]
}
function resetcolor() {
red123 = 0;
blue123 = 0;
green123 = 0;
}[/CODE]


By defining the red, green and blue variables as strings, the += operator will add a "1" character to 255, so the red value becomes "2551", then "25511" and so forth as the interval executes.

Secondly, you'll need to rebuild the colorstr variable each time the colorme function executes. Lastly, you need to clear the interval in order for it to stop, plus you need to make sure this JavaScript appears after the DIV tag in the document.
Copy linkTweet thisAlerts:
@jamesbcox1980Jul 18.2011 — There were some other problems solved here [B]but the real problem is that you're putting a semi-colon in the string value for the RGB definition:[/B]

[CODE]document.getElementById("colorthis").style.backgroundColor = "rgb(255,255,255)[COLOR="Red"][B];[/B][/COLOR]";[/CODE]

Remove that and I bet your code will work. You're not literally setting CSS here. The javascript needs to parse the value and apply it to the style object, which is a property of the element in the DOM. Once that's done, the browser will update the inline style to match.
×

Success!

Help @Leopardson spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.12,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,
)...