What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors.

Below is the snippet of my code:

$(document).ready(function() {
  let y = new Array(20);
  let x = new Array(29);
  let colors = Array.of('red','green','orange','pink','purple');
  let xCoordinate = 20
  for (let block of x) {
    let randomColor = colors[Math.floor(Math.random() * colors.length)];
    let gridBlock = $(`<div class='blockattribute' style=left:${xCoordinate}px></div>`);
    gridBlock.addClass('topcoordinate');
    gridBlock.css(`{background-color:${randomColor}}`);
    $('#colorgrid').append(gridBlock);
    xCoordinate += 20;
  }
});

The issue lies in this part of the code gridBlock.css({background-color:${randomColor}});. It seems not to be setting the color as intended. Could someone point out what I might be missing here?

Answer ā„–1

When you pass this piece of code:

`{background-color:${randomColor}}`

it will be treated as a string, not an object.

'{background-color:YOUR_COLOR}'

However, the css() function expects to receive either a properties object like:

element.css({ 'background-color': 'red' })

This means you should use:

gridBlock.css({ 'background-color': randomColor })

Alternatively, you can also pass two strings like:

gridBlock.css('background-color', randomColor);

You don't really need template strings for this particular scenario.

Answer ā„–2

Opt for template literals when specifying color and use camelCase for properties with hyphens

gridBlock.css({backgroundColor:`${selectedColor}`});

Avoid using template literals altogether.

gridBlock.css({backgroundColor:selectedColor});

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

Problems with Bootstrap affix scrolling in Internet Explorer and Firefox

I'm encountering an issue with the sidebar on my website. I've implemented Bootstrap affix to keep it fixed until the end of the page, where it should move up along with the rest of the content at a specific point... Everything seems to be worki ...

Fetching JSON data with Ajax is successful, but the information is not being displayed

I am struggling to showcase Json data from a URL in a table using ajax. The aim is for the code to iterate through the data and present it neatly in a table. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/a ...

Enable/Disable Text Editing Based on Vue Js Input

Iā€™m working on a way to make certain parts of a string in an input editable or non-editable (readonly) depending on the context in Vue.js. For instance: I have this text: My Name is $John Doe$ Now, I want my Vue.js code to scan the string and allow edi ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Using Nested ng-repeat for Values and Keys in Angular

Struggling with implementing nested ng-repeats in my code. I have a JSON object with multiple layers and attempting to iterate through them to display the data. Here is the structure of the JSON: { "status": "success", "data": { "Mat": { "tota ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. Although I thought I had a good understanding of the system ...

"Trouble with Bootstrap 4 menu: only one dropdown opens at a time

I am facing an issue where the text remains a link and the dropdown toggle works, but it is causing Dropdown-2 to open when I click on Dropdown-1. Only Dropdown-1 seems to be working properly. I can't seem to figure out why only Dropdown-1 opens no m ...

Creating a Recursive Facebook Page Data Scraper using Selenium and Node.js

I am trying to iterate through an array of Facebook page IDs and retrieve the code from each event page. However, I am encountering a problem where I only get the code of the last page ID in the array repeated multiple times. For example, if there are 3 ID ...

The image spills out of its confines

Looking to create a dialogue box that fills the entire width and height of the screen? Want to divide its content into two sections - an image and a footer area with 2 rows of height? Struggling to contain the image within its designated space without over ...

Is there a way to extract the values from a range slider individually and then display them as the minimum and maximum values on the screen?

Currently, I am facing an issue with a range slider where the value I am retrieving is concatenated. For example, when printed, it appears as 2080, with 20 and 80 being separate values visually combined on screen. My goal is to extract the minimum and maxi ...

Encountering a 500 internal server error when utilizing jQuery and Ajax with Laravel 5.2

I have been working on a post editing system using jQuery and Ajax in Laravel 5.2. But when I try to save the changes by clicking on the button inside my Bootstrap modal, an error pops up: Error: POST http://localhost:8000/edit 500 (Internal Server Error) ...

Adding a div with a canvas element is malfunctioning

I've been experimenting with using canvg to convert an SVG within a div into a canvas. So far, the conversion is working fine but when I try to copy the innerHTML of the div to another div, it's not functioning properly. The canvas is being gener ...

Sending a jQuery form to a node.js connect-form involves passing the form data through AJAX to

On the server side, I have implemented the following function as an expressjs middleware: function objCreation(req, res, next){ req.form.complete(function(err, fields, files){ if (err) { next(err); } else { // Set params in request ...

How to make the 'no data' message more noticeable in jqGrid?

When there is no data, jqGrid typically shows the message 'No records to view' within a pager (I use the top pager for my grids). However, this message can easily be overlooked. I want to change it so that the message appears below the top head ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Tips for securing a navbar in material ui

https://i.stack.imgur.com/CYfmQ.png In my current React project, I am facing an issue with aligning components within the Material-UI AppBar Component. My aim is to achieve a seamless and perfectly straight alignment for three key elements: a logo image, ...