javascripthtmljquerycsshtml-framework-7

Increase Color Value onclick from black to red Javascript


i'm working on a app and I'm trying to create a function that increases the color from black to red gradually of a number. For example the user chooses a number that goes from 0 to 100 that means he can click the button 100 times until he receives a messages saying that he can't click anymore, and I would like the color of the number getting always more red until the counter goes to the end.

Number 0 = black -> Number 100 = full red.

Here is the function that adds a number onclick:

<input type="text" id="inc" value="0" readonly="readonly"></input>

i = 0; // Default value (it's the number that shows on the counter)
x = 0; // It's the max value the user sets for the counter

function adicionar()
{
 if( i < x)
 {
  i++;
  document.getElementById('inc').value = i;
 }
}

This is what i have tried:

a = x * 50 / 100
b = x * 80 / 100
c = x * 100 / 100

if(i == a){
 var $$ = Dom7;
 $$('body').addClass('yellow');
}
if(i == b){
 var $$ = Dom7;
 $$('body').addClass('red');
}
if(i == c){
 var $$ = Dom7;
 $$('body').addClass('red2');
}

Thanks for your help!


Solution

  • let userNumberChoosen = 10 //asuuming here as 0 to 10, can be any number
    let start = 0;
    const changeColor = () => {
        const r = 255 * start/userNumberChoosen;
        const b = 0;
        const newColor ='rgb('+r+','+b+',0)';
    	document.getElementById("change").style.backgroundColor = newColor;
      start += 1.  //increment color step
    }
    <html>
      <body>
        <div> Notice my background color </div>
        <div id="change">.</div> 
        <button onClick="changeColor()">Change background</button>
      </body>
      
    </html>