0

New to JS. One thing I can't seem to wrap my head around is writing the proper code for changing an event back and forth.

For example, changing a color, back and forth on clicks, from red to black.

var titles = document.getElementById("titles");

 function changeColor()

 {
   if(titles.style.color="black")
    titles.style.color="red";
   else
   titles.style.color="black";
 };

 titles.addEventListener("click", changeColor);

I know this concept is a simple one, but when it comes to more complex things like having onclicks that open menus with other more complex things, without understanding this I'm going to have issues.

my problem is I don't understand how to control the second half of the code. I can change a color to red, but how do I change it back.

Theodore Steiner
  • 1,553
  • 2
  • 23
  • 34
  • Seems your 'second half' is already in your example code (albeit with some typo's). With more complex stuff the principle stays the same. What exactly is your question? – wintvelt May 19 '16 at 14:53
  • `titles.style.color="black"` always returns true. I guess you mean `titles.style.color == "black"` or ``titles.style.color === "black"`` – Ron van der Heijden May 19 '16 at 14:55
  • code works.. you are using one equal sign to compare – lonewarrior556 May 19 '16 at 14:57
  • here...this answer has high relevancy: http://stackoverflow.com/a/6348597/2226328. Basically you could go about it with either click events or with inline events on your markup – Frankenmint May 19 '16 at 15:00

1 Answers1

2
if(titles.style.color="black")

= is an assignment. To compare two values use === (or == if you don't want to check type as well).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • But the code with that operator corrected still doesn't work, so what am I missing? https://jsfiddle.net/theodore_steiner/pnpu1p2s/1/ – Theodore Steiner May 19 '16 at 17:10
  • @TheodoreSteiner — There's a `;` behind that link which isn't in the question. The error message in the Console of your browser's developer tools should be screaming about it. – Quentin May 19 '16 at 17:18