JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles.

The function randomly selects a border color for each circle, and this feature is functioning correctly.

To enhance the appearance, I decided to add a box shadow to the circles. However, I encountered an error while trying to implement a random color selection for the box shadow:

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

I would appreciate some guidance on how to properly assign a random color to 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;
}

Answer №1

Definition of Syntax

The term "Uncaught SyntaxError: Invalid or unexpected token" indicates that the code you have entered cannot be understood or processed by your computer.

Syntax is typically described as:

the organization of words and phrases to construct properly structured sentences in a particular language.

If you encounter a syntax error, it means there is an issue with how your code is formatted.

In case like this, you must ensure that JavaScript receives a string rather than separate properties:

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

should be modified to:

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

function createDiv(identifier, shade) {
  let div = document.createElement('div');
  div.setAttribute('id', identifier);
  if (shade === 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 = shade; 
   div.style.boxShadow = "0px 0px 15px 5px "+ shade; 
  }
  div.classList.add("circle");
  document.body.appendChild(div);
}
    
let counter = 0;

const everySecond = 1000;

setInterval(() => {
  counter += 1;
  createDiv(`div-${counter}`)
}, everySecond);
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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Promises.all fails to reach the catch block after the initial rejection

I'm completely new to promises and I'm learning how to save multiple items to a MongoDB database system. When dealing with a single item, I have a function that utilizes promises. It returns a promise that either rejects if the database save ope ...

Is it possible to utilize mathematical operators such as multiplication, division, addition, subtraction, and exponentiation to transform a non-zero numerical value into

I am currently working with Oracle Siebel software which supports JavaScript expressions using only specific operators such as multiply, divide, subtract, add, and XOR (*, /, -, +, ^). Unfortunately, other operators like ! or ? : are not available for use. ...

What is the best way to instruct Ajax to choose the specific item clicked within a list?

I am currently working on creating a list of people on vacation and I want to calculate their return date when the "Return Date" link is clicked. I have been able to achieve this, however, whenever I click any of the buttons in the list, it always passes t ...

Troubleshooting a labeling problem in a donut chart with Chart.js

$(document).ready(function(){ function call() { $.ajax({ url: "chartjs/tempdata.php", method:"GET", cache: false, success: function(data) { console.log(data); var difference=[]; var percentage=[]; var finaldata=[]; for(var i in data) { //time.push( ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

Get the selected row value from a Table and convert it into an array. Then, pass this array as a parameter to another function

I need help with logging and storing selected values from a Table component in React My Table component displays data from an API with checkboxes on each row. I'm using the <Table /> Material UI component for React. The documentation states th ...

Rotating Tetris pieces around an axis using HTML5 Canvas

I am currently working on a project and I have encountered a problem. When you press the UP key and hold it down, you will see what I mean: My goal is to make the object rotate around its axis instead of its current behavior. Please take a look at the co ...

Having trouble submitting data to a NextJS API route?

I am currently working on a simple form within a NextJS page, where the data is being stored in state: const [bookingInfo, setBookingInfo] = useState({ name: "", email: "", phone: "", }); const handleChange = (e ...

Troubleshooting: Discord bot failing to initialize on Heroku

After successfully hosting my bot on Heroku for a while, I temporarily switched back to self-hosting to update to discord.js v13. Now that I'm done with the updates and trying to re-host the bot on Heroku, I'm encountering this error: (node:4) Un ...

Get Python CSV file with Callback feature

When trying to download a CSV file from Morningstar by clicking on a button link, the presence of a callback in the URL seems to be hindering the download process. Even when pasting the URL (http://financials.morningstar.com/finan/ajax/exportKR2CSV.html?&a ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...

Creating a Node.js application using Express requires careful consideration of file structure and communication methods

Struggling to pass login form credentials to existing JavaScript files for logic and info retrieval. Login page contains a form with POST method. main.js handles the login: main.js module.exports = { returnSessionToken: function(success, error) { ...

What is the best way to handle mixed parameter types in Spring MVC when sending data from AngularJS?

I am struggling to pass a json object and a string as parameters to my Java controller. Despite my efforts, I keep receiving url = "" in the controller. What could be causing this issue? Is there a solution to successfully passing these parameters? $ ...

Ways to adjust brightness of a color using jquery

I have implemented color swatches and a slider to adjust the lightness and darkness of colors. I am seeking a way to change the lightness of the color based on the slider value. Here is what I have attempted: $("#darklight").slider({ range: "min", ...

Error: Unable to set reference. The initial argument includes an undefined value in the 'gender' property of 'Users.ji8A7TkSldfdvieDqGxko9eV3Jy1'

I followed along with a Firebase Web Tutorial on YouTube about adding data to Firebase Database for an account settings tutorial. However, when I tried to implement the code provided, it didn't work. Can anyone offer any assistance? // Code snippet fo ...

The component's width appears to be constrained by the use of display flex

I am currently working on a reactjs application that includes a header and another component. Initially, everything looks fine, but when I apply display: flex to their div, it seems to reduce the width of the header. Here are some images showing the issue: ...

Angular Bootstrap Modal provides a sleek overlay for user input forms

Trying to access an angular form within scope for validation purposes. Initial Scenario Consider the following HTML: <body ng-controller='MyAwesomeController'> <form name="fooForm"> <textarea ng-model="reason" required= ...

Angular - Detecting Scroll Events on Page Scrolling Only

I am currently working on implementing a "show more" feature and need to monitor the scroll event for this purpose. The code I am using is: window.addEventListener('scroll', this.scroll, true); Here is the scroll function: scroll = (event: any) ...

The AngularJs Wizard Validation Inputfield is unable to locate the scope

Hello all, I am new to AngularJs and encountering an issue with my code. Currently, my HTML structure looks like this: <div class="wizardContainer"> <wizard on-finish="finishedWizard()"> <wz-step title="1"> <h1>Questio ...

Limit selection choices in select element

Similar Question: Prevent select dropdown from opening in FireFox and Opera In my HTML file, I have a select tag that I want to use to open my own table when clicked. However, the window of the Select tag also opens, which is not desirable. Is there a ...