Dan Rubio Dan Rubio - 1 month ago 6
CSS Question

Why can't I use ES6 template literals with .css() method?

I am dynamically creating gridblocks where I need to dynamically change the color of every block. I am using jQuery and ES6 but I am currently experiencing a problem dynamically changing the color.

Here is 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 problem I am experiencing is this part
gridBlock.css(
{background-color:${randomColor}}
);
This code is not setting the color at all. Am I missing something here?

Answer

Because you're passing this

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

which will become a string (not an object)

'{background-color:YOUR_COLOR}'

But css() expects either a properties object like

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

Meaning you should do

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

or you can pass 2 strings like

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

You don't really need template strings for this use case.