Skip to content
Advertisement

How to pass in a variable to the CSS grid repeat() function

I am attempting create a function which involves passing in a JS variable as a term in the CSS grid repeat() function. I do not know how to do this and cannot find google results for it, below is my attempt to estimate a possible implementation.

This is for the Odin Project’s Etch-A-Sketch Project (link), and everything is vanilla.

let test = 5;

function create() {
    for (let i = 0; i < gridsize; i++) {
    div = document.createElement('div')
    div.style.backgroundColor = "#39CCCC"
    div.style.border = "2px solid black"
    div.classList.toggle("mini")
    container.addEventListener("mouseover", function(e){
  e.target.style.backgroundColor = "black";
})
    container.style.gridTemplate = "repeat(test, 1fr) / repeat(test, 1fr)"
    container.appendChild(div)
  }
}

No error messages seem to appear, and the JS containing the CSS function is simply ignored. The code runs perfectly fine as if that specific line was never written.

Advertisement

Answer

Use Template Literal strings to inject your variables into strings. Now you are outputting a string with the words test in them. And that will not be set on your element since it is not valid CSS.

You’ll want to pass the values of the variable into the string.

container.style.gridTemplate = `repeat(${test}, 1fr) / repeat(${test}, 1fr)`;

Or if you cannot use Template Literals, concatenate the string.

container.style.gridTemplate = "repeat(" + test + ", 1fr) / repeat(" + test + ", 1fr)";
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement