Stupid Dev
Stupid Dev

Reputation: 9

How can i reset my document.getElementById color value

I'm trying to change the color from red to blue but when the red color come its unchangeable

var colorvalue=0;
var sizevalue;
function CG()
{
    colorvalue ++;
    if (colorvalue==0)
    {
        document.getElementById("testd").style.color = "blue";
    }
    else if(colorvalue==1)
    {
        document.getElementById("testd").style.color = "red";
    }
    if(colorvalue > 1)
    {
        colorvalue = 0;
    }
}

I already got the answer but how do i have more colors

Thanks for seeing my question and if you do thanks for answering

Upvotes: 0

Views: 110

Answers (2)

Andy
Andy

Reputation: 63524

An alternative method would be to use CSS rather than setting the style directly on the element using JavaScript.

Initialise your text with the color red, and then toggle a blue class on/off using classList.

const test = document.querySelector('.test');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);

function handleClick() {
  test.classList.toggle('blue');
}
.test { color: red; }
.blue { color: blue; }
<p class="test">This is a test</p>
<button>Change color</button>

Upvotes: 1

ceejeey
ceejeey

Reputation: 38

i edit a bit of your code. try below

var colorvalue=0;
var sizevalue;
function CG()
{
    colorvalue ++;
    if (colorvalue % 2 == 0)
    {
        document.getElementById("testd").style.color = "blue";
    }
    else
    {
        document.getElementById("testd").style.color = "red";
    }
}

Used modulo operation: So if there is a remainder of colorvalue, element will be red.

Upvotes: 1

Related Questions