Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

kirbyrun

macrumors 6502
Original poster
Jul 26, 2009
422
617
I seriously feel like a genuine idiot posting this, but I'm in need of help. I'm just learning Javascript and I'm messing around to experiment and something dead simple that should work just won't.

I have a dummy HTML file with a text headline with the id "mainHeading." I want to change the color of that text with a click -- the first click will turn it blue, the second red. The first click works fine and the text goes from black to blue. But the second click just leaves it blue.

Here's my Javascript:

var headline = document.getElementById("mainHeading");

headline.onclick = function() {
if (headline.style.color = "black") {
headline.style.color = "blue";
} else {
headline.style.color = "red";
}
alert("The color is " + headline.style.color);

};
Not sure why it's not working. I put that alert() in there so that I could be sure the color names are right. Sure enough, after the first click, headline.style.color is blue. Which means on the second click, it should skip to the else block and go red...right? But it isn't.

Again: I'm sure I'm a complete idiot, but... Anyone want to explain to me why I'm stupid?
 
I seriously feel like a genuine idiot posting this...
Yep, you're an idiot.
All programmers are idiots. I just spent two hours to find a missing semicolon... curse the semicolons!!!!

Code:
if (headline.style.color = "black") {

Should be equality not assignment...
Code:
if (headline.style.color === "black") {

Depending on your html there may be more wrong with this.
I'd recommend using eventListeners... so much easier to debug and keeps your code neatly separated.
 
Yep, you're an idiot.
All programmers are idiots. I just spent two hours to find a missing semicolon... curse the semicolons!!!!

Code:
if (headline.style.color = "black") {

Should be equality not assignment...
Code:
if (headline.style.color === "black") {

Depending on your html there may be more wrong with this.
I'd recommend using eventListeners... so much easier to debug and keeps your code neatly separated.

Oh. My. God.

THANK YOU! Of COURSE. God, I'm a moron. (But I tell myself that being able to recognize my own moron-ness is at least a positive thing.)

Thank you again. Duh. I am off to lash myself with a scourge...
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.