Abhilekh Gautam
Abhilekh Gautam

Reputation: 655

Changing the background color using javascript

I just want the background color to be changed when the bottom is clicked using javascript.And also want to display the hex Value of the corresponding color.It should be a random selection from the code.

I actually created array of hexadecimal characters and created a function to generate the hexadecimal values.But i am unable to display the code to the screen.


var color=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];

function getRandNumber(min,max){
 return Math.floor(Math.random()*(max-min+1))+min;
}

var button = document.querySelector(".color");

button.addEventListener("click",()=>{
 document.body.style.backgroundColor = "#" 
                                     + color[getRandNumber(0,15)]
                                     + color[getRandNumber(0,15)]
                                     + color[getRandNumber(0,15)]
                                     + color[getRandNumber(0,15)]
                                     + color[getRandNumber(0,15)]
                                     + color[getRandNumber(0,15)]
                                     
 console.log(document.body.style.backgroundColor);

 document.querySelector(".colorName").innerHTML = document.body.style.backgroundColor
})

The result of console logging is in the rgb() form.Is there any way to get it in hex form.I just want to output the hex value of the background color.

Upvotes: 0

Views: 139

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22320

my way..

const a256val =()=>Math.floor(Math.random()*256)
const getHex = v =>('0'+v.toString(16)).slice(-2).toUpperCase()

function newBgColor()
  {
  let r = a256val(), g=a256val(), b=a256val()
  document.body.style.backgroundColor = `rgb(${r},${g},${b})`
  console.log(`#${getHex(r)}${getHex(g)}${getHex(b)}` )
  }

newBgColor()

Or (more "direct")

//const aRGB=()=> '#'+('0'.repeat(5)+Math.floor(Math.random()*(Math.pow(256, 3)))).toUpperCase().slice(-6)
const aRGB=()=>'#'+(Math.floor(Math.random()*0x1000000)).toString(16).toUpperCase().padStart(6,'0')

function newBgColor()
  {
  let rgb = aRGB()
  document.body.style.backgroundColor = rgb
  console.log( rgb )
  }

Upvotes: 2

ThaFog
ThaFog

Reputation: 527

toString() method takes radix as first argument so you can use it to transform number into hexadecimal representation. You'd like to use also padStart() to always have possible leading zeros if generated random is less than 0x10:

getRandNumber(0, 0xff).toString(16).padStart(2, 0) + 
getRandNumber(0, 0xff).toString(16).padStart(2, 0) + 
getRandNumber(0, 0xff).toString(16).padStart(2, 0);

or just with generating whole hex with one shot:

getRandNumber(0, 0xffffff).toString(16).padStart(6, 0) 

Upvotes: 2

Related Questions