Bek Johansson
Bek Johansson

Reputation: 21

How to change background color randomly in a javascript function

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.

Upvotes: 1

Views: 5625

Answers (6)

Pankaj Chouhan
Pankaj Chouhan

Reputation: 11

<style>
    li {
        list-style: none;
        border: solid 1px black;
        height: 25px;
        width: 25px;
        border-radius: 100px;
        text-align: center;
        float: left;
        padding: 25px;
        margin: 5px;
        background-color: aqua;
    }
</style>


<label>Enter Number: </label>
<input type="text" id="box_no">
<button onclick="changeColor()">Result</button>

<ul id="print">
</ul>

<script type="text/javascript">

    function generateNewColor() {
        const hexCharacters = '0123456789ABCDEF';
        let hexColorRep = "#";
        for (let i = 0; i < 6; i++) {
            hexColorRep += hexCharacters[Math.floor(Math.random() * 16)];
        }
        return hexColorRep;
    }

    function changeColor() {
        let list = parseInt(document.getElementById("box_no").value);
        let print_data = document.getElementById("print");
        print_data.innerHTML = ''; // Clear previous content
        for (let i = 0; i < list; i++) {
            let listItem = document.createElement('li');
            listItem.style.backgroundColor = generateNewColor();
            listItem.textContent = i + 1;
            print_data.appendChild(listItem);
        }
    }
</script>

Upvotes: -1

Bhaskar Saini
Bhaskar Saini

Reputation: 1

This is how I learn to create random colors by changing HEX values

const randomColor = function(){
  const hex = '0123456789ABCDEF'; //hex colors range
  let color = '#';
  for(let i=0;i<6;i++){
    color += hex[Math.floor(Math.random()*16)];
  }
  return color;
}
console.log(randomColor()) //to verify our color

I hope you find it helpful!

Upvotes: 0

Irene Cantero
Irene Cantero

Reputation: 1

This function works perfectly.

function clickChangeBg() {

    let randomColor = Math.floor(Math.random()*16777215).toString(16);
    let rgbValue = "#" + randomColor;
    document.body.style.backgroundColor = rgbValue;
}

Upvotes: 0

Abir Tasrif Anto
Abir Tasrif Anto

Reputation: 1

Changing the background with random hex colors everytime page loads or refresh

const hexDigits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "a", "b", "c", "d", "e", "f"];

function generateRandomColor(hexDigits) {
  let bgColor = "#";

  for (let i = 0; i < 6; i++) {
    const index = Math.floor(Math.random() * hexDigits.length);
    bgColor += hexDigits[index];
  }
  return bgColor;
}

function changeBgColor() {
  const color = generateRandomColor(hexDigits);
  document.body.style.backgroundColor = color;
}

window.addEventListener("load", changeBgColor());

Upvotes: 0

Albert Badias
Albert Badias

Reputation: 118

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!

Upvotes: 0

Albert Badias
Albert Badias

Reputation: 118

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

Upvotes: 4

Related Questions