Newbie Javascript help!

Discussion in 'Web Design and Development' started by kirbyrun, Sep 5, 2015.

  1. kirbyrun macrumors member

    Joined:
    Jul 26, 2009
    #1
    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?
     
  2. 960design macrumors 68000

    Joined:
    Apr 17, 2012
    Location:
    Destin, FL
    #2
    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.
     
  3. kirbyrun thread starter macrumors member

    Joined:
    Jul 26, 2009
    #3
    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...
     

Share This Page