Home > Software engineering >  Assign document.body.style.backgroundColor to a variable
Assign document.body.style.backgroundColor to a variable

Time:09-17

I'm making a simple color changer. And I assigned document.body.style.backgroundColor to valuable backgroundColor. When I console.log(backgroundColor) , I can see it's working but background color doesn't change. So I just deleted the variable backgroundColor and put document.body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; and then it works! But I can't understand why it doesn't work when I assigned document.body.style.backgroundColor to a variable as below code.

const btn = document.querySelector('.btn');
const color = document.querySelector('.color');
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];

btn.addEventListener('click', function() {
    
    let backgroundColor =  document.body.style.backgroundColor ;
    backgroundColor  = colors[Math.floor(Math.random() * colors.length)];
  
console.log(backgroundColor)

})

CodePudding user response:

By doing that you are just copying (saving) the literal value of the document.body.style.backgroundColor, not a thing to point at that. so assigning a new value to the variable doesn't affect the document.body.style.backgroundColor.

You are just changing the value again:

backgroundColor  = colors[Math.floor(Math.random() * colors.length)];
  • Related