Dan Rubio Dan Rubio - 1 year ago 60
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>`);
xCoordinate += 20;

The problem I am experiencing is this part
This code is not setting the color at all. Am I missing something here?

Answer Source

Because you're passing this


which will become a string (not an object)


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download