0

I am trying to change the color of an element using .style.color and it isn't going very smoothly. My goal is for it to change red and then blue on clicks. Any recommendations?

var turns = 0;

function dot_01() {
    if (turns === 0) {
        turns++;
        document.getElementById("dot_01").style.color = 'red';
     } else if (turns === 1) {
        turns--;
        document.getElementById("dot_01").style.color = 'blue';
    }
}

<div class="dot" id="dot_01" onclick="dot_01()"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
Benn
  • 55
  • 1
  • 1
  • 8
  • what does smoothly mean for you? – raviolican May 15 '18 at 23:19
  • it isnt working – Benn May 15 '18 at 23:19
  • Possible duplicate of [Change Button color onClick](https://stackoverflow.com/questions/26937424/change-button-color-onclick) –  May 15 '18 at 23:27
  • Marking this as dupe of the first search result for the title, given that the [answer](https://stackoverflow.com/a/26937544/5734311) addresses OP's issues perfectly. –  May 15 '18 at 23:28

3 Answers3

1

You want to use .style.backgroundColor to change the button color. .color is going to change the font color.

<input type="button" value="Click Me" onclick="this.style.backgroundColor = '#000'; this.style.color = '#FFF';" />
Thomas
  • 442
  • 4
  • 11
  • Question, any way to shorten it instead of saying document.getElementbyId, I know you can use variables, please demonstrate. – Benn May 15 '18 at 23:25
  • Yes. You can put the element in to a variable. `let elm = document.querySelector("#testitem");` Then you can interact with the variable `elm` as if it were the element. `elm.style.backgroundColor = '#ACD';` – Thomas May 15 '18 at 23:28
  • Doesnt seem to work ;/ let d1 = document.querySelector("dot_01"); d1.style.backgroundColor = '#e22b2b'; – Benn May 15 '18 at 23:34
  • What you wrote works perfectly for me. I would check two things. Possibly your browser does not support using `let`. In this case, you can change that to `var` and it should work. If it does not work, be sure that an element with the ID "d1" definitely exists on the page you're running this. – Thomas May 15 '18 at 23:37
1

If you mean to change the background color try style.backgroundColor like the following way:

document.getElementById("dot_01").style.backgroundColor = 'red';
function dot_01(el) {
  if (el.style.backgroundColor === 'red') {
    el.style.backgroundColor = 'blue';   
  }
  else el.style.backgroundColor = 'red';
}
<div class="dot" id="dot_01" onclick="dot_01(this)">Container</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

I'm using this to change styling, it's a very simple JavaScript that changes the display and height properties of the CSS to show / hide a container. Sorry I haven't changed it to your desired outcome yet but I hope this helps, just modify it to change the color by doing something like:

style="color:red"

https://jsfiddle.net/raydekker/u821a84d/

style="color:red";
Ray
  • 156
  • 1
  • 2
  • 14