Home > OS >  How to change background color randomly in a javascript function
How to change background color randomly in a javascript function

Time:11-06

I would appreciate any help. I want to change the text color of the button every time it is a darker background color. I have been trying other variations of the below code. I cant seem to get the newColor to work. Thanks in advance for your help.

const button = document.querySelector('button');
const h1 = document.querySelector('h1');
button.addEventListener('click', () => {
    const newColor = randomColor();
    document.body.style.backgroundColor = newColor;
    h1.innerText = newColor;
})


let newColor;

const randomColor = () => {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    newColor =  r * 0.299   g * 0.587   b * 0.114
    if(newColor > 186) {
        newColor = 'black';
    } else {
        newColor = 'white';
    }
    return `rgb(${r}, ${g}, ${b})`;
}

I tried making my own function, I have tried putting an if statement on the outside of the function.

CodePudding user response:

You can use the follow code:

var newRandomColor = Math.floor(Math.random()*16777215).toString(16)

This code works for generate random colors. Hope it helps you

CodePudding user response:

For specifically an RGB color code you can use:

function RGBcolor() {
  var R = Math.floor(Math.random() * 256);
  var G = Math.floor(Math.random() * 256);
  var B = Math.floor(Math.random() * 256);
  var randomcolor = "rgb("   R   ","   G   ","   B   ")";  
  console.log(randomcolor);
}

RGBcolor();

Hope it helps too!

  • Related