What is the best way to ensure a CSS element maintains its position margins even after adjusting them with JavaScript?

Currently, I am in the process of developing a minesweeper game using a combination of HTML, CSS, and JavaScript. The code snippet I am utilizing to generate the grid is as follows:

<div id="game-space"></div>

<script type="text/javascript">
  for(i=0; i<40; i=i+20){
    var k = 450 + i;
    document.getElementById("game-space").style.position = "relative";
    document.getElementById("game-space").style.top = "100px";
    document.getElementById("game-space").style.left = k + "px";
    document.getElementById("game-space").style.backgroundColor = "black";
    document.getElementById("game-space").style.display = "block";
  }
</script>

My aim is to increment the left margin by 20px with each iteration of the loop to construct a row.

However, I am encountering a challenge whereby, as illustrated in the code snippet, the loop is intended to execute twice, resulting in two black blocks being displayed. Nevertheless, only a single block is displayed at the ultimate loop position.

Could someone provide guidance on how I can maintain the blocks throughout the loop progression?

Answer №1

To generate a new div element for each box you wish to create, you must follow this process:

var newBox = document.createElement('div');
document.getElementById("game-space").appendChild(newBox);

Below is your updated code with distinct indexes assigned to all the div elements

<div id="game-space"></div>

<script type="text/javascript">
  var gameSpace = document.getElementById("game-space");
  for(i=0; i<2; i++){
    var leftOffset = 450 + i*20;
    var newBox = document.createElement('div');
    
    newBox.id = "game-space-" + i;
    newBox.style.position = "absolute";
    newBox.style.top = "100px";
    newBox.style.left = leftOffset + "px";
    newBox.style.backgroundColor = "gray";
    newBox.style.borderStyle = "solid";
    newBox.style.height = "20px";
    newBox.style.width = "20px";
    newBox.style.display = "block";

    gameSpace.appendChild(newBox);
  }
</script>

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

Personalize the position of the v-select drop-down menu

I am currently working with the vuetify v-select component. The problem I am encountering is that instead of the dropdown opening downwards, I need it to open upwards since the dropdown is positioned at the bottom of the page which causes some of the dro ...

transforming basic pagination using javascript to jquery implementation

I have a straightforward pagination code written in raw JavaScript. function UpdatePage(e){ if(busy == 0) { switch(e) { case "Next": page = p+1; p++; break; ca ...

Getting the value of an HTML tag returned from an Ajax request

After making an AJAX call in VBScript, I am receiving the following HTML: <html> <body> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td width="100%" ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Choose a word at random from a JSON string

Utilizing JSONP, I have successfully retrieved a list of words from an external source to randomly select one for use in a game. The current source being used is as follows: function processResult(obj) { console.log(obj); var data = ...

CSS: Set the left position to 250px with the added feature of hiding any overflow

I am currently working on a sidebar that can be shown or hidden using JavaScript with CSS animations. To achieve this effect, I need to position the content div (#main) using left: 250px;. #main { left: 250px; position: relative; overflow: hidden; } ...

Adjust the text color of a particular word as you type using the contenteditable property set to "true"

I'm attempting to jazz things up a bit. For instance, I have a div that is set as contenteditable="true". What I want to achieve is changing the color of a specific word I type while writing. In this case, let's say the word "typing" sh ...

Using JQUERY to create a dropdown menu that dynamically changes based on the date field

I am currently working on a JQUERY project and facing a challenging situation. I usually know how to create dropdown menus that depend on one another, but this time I need a dropdown menu that displays age ranges based on the date entered in the birth-date ...

Improving access for disabled individuals in HTML through tab-index usage

Hey there, I'm currently dealing with some challenges regarding tab-index for disabled elements. It seems that we are unable to focus on the elements, as screen reader tools are not announcing them and are skipping over them directly. For example: I ...

What is the best way to choose a range of nodes with dynamic limitations without relying on static positions?

<li></li> <th> <li></li> <strong>"Jeff"<strong> <li></li> <a>"Mary"<a> <li></li> <th> <li></li> <strong>"Rich"<strong> <li></li&g ...

Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highl ...

Vertical Alignment Challenge in Bootstrap Container

I'm struggling with formatting my simple website. I have a navbar, footer, and a centered container where I want to display text and buttons. However, I can't seem to get the elements to appear on separate lines - I want the text on one line and ...

I am having trouble retrieving a JsonResult from an asp.net mvc controller using $resource in angular

I am new to Angularjs and trying to integrate it with asp.net mvc. I am facing an issue where I am unable to access an asp.net mvc controller to return a JsonResult using $resource in angular. Strangely, when I use $.getJson in JavaScript directly, it work ...

Unable to compile relative path of threejs using browserify and babel

As a newcomer to babel and browserify, I encountered an issue while trying to transpile with browserify and babel. After installing the threejs package and adding the following import: import * as THREE from 'three' Everything worked fine when t ...

Instructions for submitting a form using Xcode

How can I automate the submission of a form in a webview? Here is my code: #import <Cocoa/Cocoa.h> #import <WebKit/WebKit.h> #import <WebKit/WebResourceLoadDelegate.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @pro ...

What is the process for transforming a promise outcome into JSON format?

My current challenge involves using axios to retrieve JSON data from an external API in my backend and then passing it to the frontend. The issue arises when I attempt to log the result in the frontend, as all I see is a promise object instead of the actua ...

What is the best way to remove specific items from an AngularJS ng-repeat loop?

Is there a way to filter out certain items in an ng-repeat loop? For instance, consider the following simplified code snippet: <div class="row" data-ng-repeat="entry in data.feed.entry | orderBy:'gsx$timestamp.$t':true"> {{entry.gsx$jobID ...

Finding the absolute root path of a npm package in Node.js

Objective I am on a quest to find a reliable method to ascertain the absolute root path of an npm package that has been installed in Node.js. Challenge Although I am aware of require.resolve, it only provides the entry point (path to the main module) an ...

combine two 2D arrays in JavaScript

I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In oth ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...