Home > OS >  Random color for boxShadow javascript
Random color for boxShadow javascript

Time:03-13

I have a function that randomly creates divs with circles.

It has a random color choice for the border. It works as it should.

I also added a box shadow, and I want the color to change the same way as the border.

I did everything by analogy as with the border, but I get an error:

"message": "Uncaught SyntaxError: Invalid or unexpected token"

How can I set a random color for the box shadow?

function createDiv(id, color) {
  let div = document.createElement('div');
  div.setAttribute('id', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.borderColor = colors[Math.floor(Math.random() * colors.length)];
    div.style.boxShadow = 0px 0px 15px 5px colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.borderColor = color; 
   div.style.boxShadow = 0px 0px 15px 5px color; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
let i = 0;

const oneSeconds = 1000;

setInterval(() => {
  i  = 1;
  createDiv(`div-${i}`)
}, oneSeconds);
div {
  display: inline-block;
  margin: 20px;
}

.circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  background-color: #ffffff;
  border: 3px solid #000;
  box-shadow: 0px 0px 15px 5px #0ff;
  margin: 20px;
}

CodePudding user response:

Syntax

"Uncaught SyntaxError: Invalid or unexpected token" basicly means your computer can't parse/understand the code you provided.

Syntax is defined as:

the arrangement of words and phrases to create well-formed sentences in a language.

when you see a syntax error; it's because your code is malformed.

In this specific case you would need make sure the js receives a string instead of seperate properties:

   div.style.boxShadow = 0px 0px 15px 5px color; 

becomes

   div.style.boxShadow = "0px 0px 15px 5px "  color; 

function createDiv(id, color) {
  let div = document.createElement('div');
  div.setAttribute('id', id);
  if (color === undefined) {
    let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
    div.style.borderColor = colors[Math.floor(Math.random() * colors.length)];
    div.style.boxShadow = "0px 0px 15px 5px " colors[Math.floor(Math.random() * colors.length)];
  }
  else {
   div.style.borderColor = color; 
   div.style.boxShadow = "0px 0px 15px 5px "  color; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
let i = 0;

const oneSeconds = 1000;

setInterval(() => {
  i  = 1;
  createDiv(`div-${i}`)
}, oneSeconds);
div {
  display: inline-block;
  margin: 20px;
}

.circle {
  width: 80px;
  height: 80px;
  border-radius: 80px;
  background-color: #ffffff;
  border: 3px solid #000;
  box-shadow: 0px 0px 15px 5px #0ff;
  margin: 20px;
}

  • Related