Can you please explain how the repeat() function functions? I would like to understand it better

Currently diving into the world of Javascript, I came across this interesting method to create a 16X16 grid using example.repeat(number) with a numerical value. While I have a general understanding of the code flow, I'm struggling to fully grasp how the 'repeat' function works in this context. Any insights would be greatly appreciated!

Check out the 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"));

Answer №1

It seems like your question doesn't pertain to JavaScript, but rather to the CSS repeat function.

The repeat() function in CSS allows for a repeated pattern of columns or rows to be written more concisely in the track list.

If you want to learn more about this function, you can visit the MDN reference here:

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

Answer №2

In this code snippet, each line is commented to help you better understand how it works.

function createGrid(xSize, ySize, cellSize, gridContainer) { // Function declaration for creating a grid with specified parameters
    gridContainer.style.display = "grid"; // Set the display style of the grid container to grid
    gridContainer.style.gridTemplateColumns = `repeat(${xSize}, ${cellSize}px)`; // Define the number of columns in the grid based on cell size
    gridContainer.style.gridTemplateRows = `repeat(${ySize}, ${cellSize}px)`; // Define the number of rows in the grid based on cell size
   
    let cellsFragment = new DocumentFragment(); // Create a document fragment to hold the grid cells
  
    for (let i = 0; i < xSize * ySize; i++) { // Loop to create individual grid cells
      let cell = document.createElement('div'); // Create a div element for each cell
      cell.className = 'cell'; // Assign the class name 'cell' to the created cell
      cellsFragment.appendChild(cell); // Append the cell to the fragment
    }
  
    gridContainer.appendChild(cellsFragment); // Add all grid cells to the grid container
  }
  
  
  createGrid(16, 16, 25,  document.querySelector(".grid-container")); // Call the createGrid function with specific parameters to build the grid

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

Ajax request causing bootstrap success message to have shorter visibility

I encountered an issue with my ajax form that retrieves data using the PHP post method. Instead of utilizing the alert function in JavaScript, I decided to use a bootstrap success message. However, there is a problem as the message only appears for less th ...

Using the toggle method or IF statements in JavaScript to implement show and hide functionality upon clicking

I’ve been struggling with this issue for days now. It seems like I may have overcomplicated a simple piece of code. I'm trying to show some divs when a button is clicked, but I’m having trouble getting it to work properly. Initially, I used VAR.st ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

Tips for swapping content between table rows in JavaScript

Struggling to rearrange a table with a new order due to performance issues. Here is a simplified version of the structure: <table> <tr id="row1"></tr> <tr id="row2"></tr> <tr id="row3"></tr> <tr id="row4">&l ...

Hide form data upon submission

I have a form and I'm looking to send hidden input using JavaScript. How can this be achieved? Example: <input id="total" type="hidden" value="" name="total" /> When the submit button is clicked, I would like to set its value. ...

Is Three.js deprecating the setHSL() function?

Searching for a solution to incorporate an HSL color scheme into my threejs project. The documentation seems to lack information on using .setHSL() or .offsetHSL() post-2013. Is there a preferred method to exclusively utilize HSL in a threejs scene? Appre ...

Display an error message whenever the mouse leaves the input field

Can someone please help me with how to display an error message in Angular4 when the input field is required and the mouse leaves the input? I want the error to show only when the mouse leaves the input, not while I am typing within the input field. Here ...

Hovering causes adjacent elements to shift to the right

Whenever I hover over one of the long <li> elements, the other elements shift to the right. To view the fiddle code, click on the link below: .footer_links{ margin-top:60px; } footer .ourServices{ ...

TypeError is encountered while attempting to verify cookies

I created a function like this: const token = req.cookies['SESSION_DATA'] if (token) { ... } catch (err) { ... } However, when I try to check for a token, I receive a TypeError stating "Cannot read property of undefined." Interestingly, the same ...

What could be causing the error with VITE_ENV in my project?

I am currently working on a project and I'm looking to utilize VITE_ENV for accessing environmental variables in place of using dotenv, even though I already have the dotenv package installed. The example I followed can be found in vite's docume ...

Getting access to props within a child component's mounting phase

It is commonly understood that when the child component is mounted before the parent component, trying to access props in the child component's mounted period will result in null. However, I recently came across a scenario where props were successful ...

prompting users in a node.js application

I need help with querying the user multiple times in my Node.js application. Currently, all responses get printed out together and the first response is processed by both functions. I suspect this issue arises from the asynchronous nature of Node.js. Can s ...

Issue with animated SVG failing to display in web browser

I created an animated .svg file that you can view here, but I encountered an error when trying to open it in the browser: https://i.sstatic.net/YMf5L.png The color appears different, even though the code remains the same. <svg id="Layer_2" data-name ...

Dividing a string in JavaScript to generate fresh arrays

I am currently dealing with the following string: "ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0 ...

Attain three images with precise dimensions using CSS

Having trouble fitting 3 images in the same row? The issue arises when the images have different sizes, causing everything to shift. Any advice on how to address this problem? Thank you. HTML: <div class="first-slot"> <di ...

Typemoq and Angular-cli are incompatible with each other

Many Angular 2 cli applications come with karma-jasmine tests already set up. If you decide to enhance your tests by using typemoq, simply run the command npm install typemoq --save-dev Then, include typemoq in one of your test files like this: ...

Exploring the attributes of optional features

Dealing with optional properties can be quite tedious. Consider the object test1 in TypeScript: interface Test { a?: { b?: { c?: { d?: string } } }; } const test1: Test = { a: { b: { c: { d: 'e' } } } }; Handling the absence of each proper ...

When attempting to make a GET request, Express/Mongoose is returning a null array

I am having trouble retrieving the list of books from my database. Even though I have successfully inserted the data into Mongoose Compass, when I try to fetch it, all I get is an empty array. //Model File import mongoose from "mongoose"; cons ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...