Home > Software design >  How does this repeat() function work? Help me understand
How does this repeat() function work? Help me understand

Time:06-30

I'm learning Javascript and found this solution on how to make a 16X16 grid. so far i've used example.repeat(number) with a an integer value. I somewhat get the flow of the code but I cant grasp how repeat works here exactly, kindly help.

Result on codepen: https://codepen.io/shogunhermit15/pen/mdxyqMN?editors=1010

function buildGrid(x, y, cellSize, gridElement) {
  gridElement.style.display = "grid";
  gridElement.style.gridTemplateColumns = `repeat(${x}, ${cellSize}px)`;
  gridElement.style.gridTemplateRows = `repeat(${y}, ${cellSize}px)`;
 
  let squares = new DocumentFragment();

  for (let i = 0; i < x * y; i  ) {
    let square = document.createElement('div');
    square.className = 'square';
    squares.appendChild(square);
  }

  gridElement.appendChild(squares);
}


buildGrid(16, 16, 25,  document.querySelector(".grid"));

CodePudding user response:

I think your question is not related to javascript. It is related to the CSS repeat function.

The repeat() CSS function represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form.

Here is Mdn refrence where You can learn more:

https://developer.mozilla.org/en-US/docs/Web/CSS/repeat

CodePudding user response:

You will find here your code with each line commented, hoping that it helps you to understand your code correctly.

function buildGrid(x, y, cellSize, gridElement) { // declaration of the buildGrid function which takes as parameters the location of the grid, the size of the cell, and the element of the grid
    gridElement.style.display = "grid"; // grid display is set to grid
    gridElement.style.gridTemplateColumns = `repeat(${x}, ${cellSize}px)`; // set grid size based on cell size
    gridElement.style.gridTemplateRows = `repeat(${y}, ${cellSize}px)`; // set grid size based on cell size
   
    let squares = new DocumentFragment(); // creating the squares object which contains the grid elements
  
    for (let i = 0; i < x * y; i  ) { // loop that creates grid cells
      let square = document.createElement('div'); // creating a div element
      square.className = 'square'; // adding square class to cell
      squares.appendChild(square); // adding the cell to the grid
    }
  
    gridElement.appendChild(squares); // adding grid to page element
  }
  
  
  buildGrid(16, 16, 25,  document.querySelector(".grid")); // call buildGrid function with defined parameters
  • Related