Benn
Benn

Reputation: 55

Change Color onClick

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>

Upvotes: 0

Views: 14955

Answers (3)

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 1

Ray
Ray

Reputation: 186

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";

Upvotes: 0

Thomas
Thomas

Reputation: 442

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';" />

Upvotes: 1

Related Questions