HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't seem to adhere to the width and height values set in the JavaScript file. Instead, it generates div elements with a width of 0 and stretched height. What could I be doing wrong?

const okBtn = document.querySelector('#ok-button')
okBtn.addEventListener('click', () => {
  const size = document.querySelector("#grid-size").value
  drawGrid(size)
})


const BOX = document.querySelector("#drawing-space")
const BOXsize = BOX.offsetWidth

function drawGrid(size) {
  var cellSize = BOXsize / size
  console.log()
  for (let i = 0; i < size * size; i++) {
    const cell = document.createElement('div')

    cell.classList.add('cell')
    BOX.appendChild(cell)
    cell.width = cellSize
    cell.height = cellSize
    console.log("appended #", i)
    console.log(cell.offsetWidth)
    console.log(cell.offsetHeight)

  }
}
body {
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  height: 100vh;
}


/* HEADER */

#header {
  display: flex;
  font-size: 90px;
  justify-content: center;
  align-items: center;
  background-color: #1A1A1D
}

#header .tittle {
  color: aliceblue;
  font-family: 'Shadows Into Light', cursive;
}

img {
  font-size: 40px;
  font-style: italic;
}


/* MAIN */

.main {
  background-color: rgb(192, 213, 231);
  font-size: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.main #reset-button {
  font-family: 'Shadows Into Light', cursive;
}

#size-settings {
  display: flex;
  font-size: 50px;
  font-family: 'Shadows Into Light', cursive;
}

#size-settings #size-input input {
  margin: 5px;
  margin-right: 10px;
  background-color: rgb(192, 213, 231);
  width: 60px;
  height: 60px;
  font-size: 45px;
  font-family: 'Shadows Into Light', cursive;
}

#reset-button:hover {
  transform: scale(1.3);
  color: aliceblue;
}

#ok-button:hover {
  transform: scale(1.3);
  color: aliceblue;
}

#drawing-space {
  width: 900px;
  height: 900px;
  border: #1A1A1D 4px solid;
}

#drawing-space {
  display: flex;
  flex-flow: row wrap;
}


/* CELL */

.cell {
  border: #C3073F solid 1px;
  flex: 0 0 auto;
}


/* FOOTER */

#footer {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #C3073F;
  margin: 0px;
}

#footer .text {
  font-size: 40px;
}


/* ICONS */

.material-symbols-outlined {
  font-size: 100px;
  color: aliceblue;
  font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 48
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Shadows+Into+Light&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e5a2b7a4a1a5d7d5cbcbd1dd">[email protected]</a>,100..700,0..1,-50..200" />
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div id="header">
    <div class="tittle">SKETCHBOOK</div>
    <div id="pen-icon">
      <div class="material-symbols-outlined">edit</div>
    </div>
  </div>

  <div class="main">
    <div id="reset-button">RESET</div>
    <div id="size-settings">
      <div class="text">SIZE:</div>
      <div id="size-input"><input id="grid-size" type="number" for="text" min="1" max="99"></div>
      <div id="ok-button">OK</div>
    </div>

    <div id="drawing-space">

    </div>

  </div>
  <div id="footer">
    <div class="text"> by mt 2022</div>
  </div>

  <script src="script.js"></script>
</body>

</html>

CodePen: https://codepen.io/mttt7/pen/RwyavzB

Answer №1

The issue lies in the incorrect way you are setting the width and height.

There are two key problems here: firstly, you need to call the style object when applying inline styles, and secondly, you are missing units for both measurements.

To resolve this, you can update it as follows:

cell.style.width = `${cellSize}px`;
cell.style.height = `${cellSize}px`;

const okBtn = document.querySelector('#ok-button')
okBtn.addEventListener('click', () => {
  const size = document.querySelector("#grid-size").value
  drawGrid(+size)
})


const BOX = document.querySelector("#drawing-space")
const BOXsize = BOX.offsetWidth

function drawGrid(size) {
  var cellSize = BOXsize / size;
  for (let i = 0; i < size * size; i++) {
    const cell = document.createElement('div');

    cell.classList.add('cell');
    BOX.appendChild(cell);
    cell.style.width = `${cellSize}px`;
    cell.style.height = `${cellSize}px`;
   // console.log("appended #", i)
    //console.log(cell.offsetWidth)
    //console.log(cell.offsetHeight)

  }
}
body {
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  height: 100vh;
}


/* HEADER */

#header {
  display: flex;
  font-size: 90px;
  justify-content: center;
  align-items: center;
  background-color: #1A1A1D
}

#header .tittle {
  color: aliceblue;
  font-family: 'Shadows Into Light', cursive;
}

img {
  font-size: 40px;
  font-style: italic;
}


/* MAIN */

.main {
  background-color: rgb(192, 213, 231);
  font-size: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.main #reset-button {
  font-family: 'Shadows Into Light', cursive;
}

#size-settings {
  display: flex;
  font-size: 50px;
  font-family: 'Shadows Into Light', cursive;
}

#size-settings #size-input input {
  margin: 5px;
  margin-right: 10px;
  background-color: rgb(192, 213, 231);
  width: 60px;
  height: 60px;
  font-size: 45px;
  font-family: 'Shadows Into Light', cursive;
}

#reset-button:hover {
  transform: scale(1.3);
  color: aliceblue;
}

#ok-button:hover {
  transform: scale(1.3);
  color: aliceblue;
}

#drawing-space {
  width: 900px;
  height: 900px;
  border: #1A1A1D 4px solid;
}

#drawing-space {
  display: flex;
  flex-flow: row wrap;
}


/* CELL */

.cell {
  border: #C3073F solid 1px;
  flex: 0 0 auto;
}


/* FOOTER */

#footer {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #C3073F;
  margin: 0px;
}

#footer .text {
  font-size: 40px;
}


/* ICONS */

.material-symbols-outlined {
  font-size: 100px;
  color: aliceblue;
  font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 48
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Shadows+Into+Light&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14534655505426243a3a202c">[email protected]</a>,100..700,0..1,-50..200" />
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div id="header">
    <div class="tittle">SKETCHBOOK</div>
    <div id="pen-icon">
      <div class="material-symbols-outlined">edit</div>
    </div>
  </div>

  <div class="main">
    <div id="reset-button">RESET</div>
    <div id="size-settings">
      <div class="text">SIZE:</div>
      <div id="size-input"><input id="grid-size" type="number" for="text" min="1" max="99"></div>
      <div id="ok-button">OK</div>
    </div>

    <div id="drawing-space">

    </div>

  </div>
  <div id="footer">
    <div class="text"> by mt 2022</div>
  </div>

  <script src="script.js"></script>
</body>

</html>

Answer №2

When considering the objectives of your application and the necessary updates, it is important to adjust the following:

cell.style.width = `${cellSize}px`;
cell.style.height = `${cellSize}px`;

Furthermore, make sure to modify this section as well:

const BOXsize = BOX.offsetWidth

function drawGrid(size) {
  var cellSize = BOXsize / size;
  ...
  }
}

To achieve desired results, update it to:

const BOXsize = BOX.clientWidth;

function drawGrid(size) {
    var cellSize = (BOXsize - 2 * size)/ size;
    ...
}

The adjustment is required due to variations between offsetWidth and clientWidth, in addition to the border size set for the div element.

The revised formula should be:

cellSize = (BOXsize - (border size of div) * 2 * size)/ size

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

How can I access the feed of a single user using the Facebook API

I have yet to experience working with Facebook APIs, but I am interested in developing a basic app that will display posts from a specific Facebook user. I would prefer not to enable login for multiple users, just keep it simple. My goal is to create an a ...

Is there a way to adjust the font size for the label in mat-step?

Is there a way to update the design using only inline styles and CSS? Below is the code snippet I am working with: <div class="statusbar"> <mat-horizontal-stepper linear > <mat-step label="One" [complet ...

Recording a specialized event sent from a web component to React

Trying to incorporate a Lit web component into a React application has presented some challenges for me. This web component is expected to dispatch a custom event at some point, and I need to handle it in the React application appropriately. Despite my li ...

Comparison of Chrome's compatibility with Bootstrap and Edge

Firefox Safari I am facing an issue that seems obvious, but I am unable to pinpoint the exact cause. It just doesn't seem right for no apparent reason. is the website in question. I have tried various troubleshooting methods such as inspecting th ...

Dependency of multiple objects in Webgl three.js

I'm struggling with object dependencies and need help. I want to create a setup where one object is dependent on two other objects. Essentially, when I modify the position of one parent object (like changing the y-Position), the dependent object (chil ...

Is the scaling of a div with an image affected by odd pixel sizes?

My goal is to create a responsive grid with square images, where the first image is double the size of the others. While I can achieve this using jQuery, I am curious if there's a way to accomplish this purely with CSS. Grid: Here's an example o ...

Retrieve a collection of JSON files using a single function

The format of JSON links is as follows: www.example.com/link-number-end-of-link.com.json I need to retrieve multiple JSON link files where the only variable changing is the number in the link. For example, it could range from 10 to 40, with the first ...

Guide to implementing a universal animated background with Angular components

I'm having trouble figuring out why, but every time I attempt to use a specific code (for example: https://codepen.io/plavookac/pen/QMwObb), when applying it to my index.html file (the main one), it ends up displaying on top of my content and makes ev ...

Guide on stacking two divs on each other in response to a decrease in screen width

In this particular section, there is a div labeled programDescriptionDiv. Inside programDescriptionDiv, there are two separate divs. Normally, these two divs each take up 50% of the screen width. The goal is to have the second div stack below the first on ...

Using the @ Symbol in Javascript ES6 Module Imports

One of the folders in my node_modules directory is called @mymodule, and within it, there is another folder named 'insidefolder'. The path to this folder looks like this: node_modules/@mymodule/insidefolder When trying to import insidefolder us ...

Issues have arisen with the execution of JavaScript code inside a callback function

When the warnBeforeNew variable is set to false in the JavaScript code below, the file open function works as expected. However, when warnBeforeNew is true, an error occurs stating "Uncaught TypeError: Cannot read property 'root' of undefined". ...

Add several additional views following an element within a View in Backbone

addDimensions: function (order_id, counter) { this.dimensionsView = new dimensionsView({ el: "#panel-boxes-" + order_id + "_" + counter, id: order_id, counter: counter }); $("#panel-boxes-" + order_id + "_1").append(this.dimensionsView.render().el) ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Manipulate HTML Elements with a Click of a Button in React

Is there a straightforward method to replicate this jQuery example using only React, without relying on jQuery or other external libraries? I'm still developing my ReactJS skills and hoping for guidance on dynamically creating and deleting elements. ...

Align labels on top and inputs at the bottom using Bootstrap

I'm facing an issue with alignment in my form using Bootstrap 4.4. Whenever a select element is included, it disrupts the layout by breaking the alignment of labels and inputs on the same row. Is there a way to always keep the labels at the top and t ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Using Javascript to Treat an HTML Document as a String

Check out the complete project on GitHub: https://github.com/sosophia10/TimeCapsule (refer to js/experience.js) I'm utilizing JQuery to develop "applications" for my website. I'm encountering a problem where I can't locate the correct synta ...

Is there a way to stack multiple divs on top of each other in my HTML login page?

Below is the HTML code for my form: <div style="display:block; margin:0 auto;"> <h2>Welcome</h2> </div> <div id="box"> <div id="box2"> <p id="pid"><b>Em ...

Buttons are to be placed at the identical location

Here is the HTML code I am working with: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33545c5446734a525b5c5c1d505c5e">[email protected]</a> wants to be your partner. Do you agree? <br><input type="but ...

<div> issues with background display

I have created two different sections with distinct backgrounds. However, I am facing an issue where these two divs are not appearing on the webpage. My intention is to position the Navbar at the top and have another section below it that is not linked to ...