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

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

Add an event to your Fullcalendar with a date that is not the same as the present date in your MySQL database

I currently have Fullcalendar set up to display events from a MySQL table (title + datetime) and allow users to add new events by clicking on a specific day within the calendar. However, I am facing an issue where it only adds events to the current day ev ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

The feature to toggle push notifications is missing in Xcode 11, and is also not available in the capability settings

I'm currently developing an Ionic project and trying to incorporate FCM Push notifications. I am unable to locate the toggle push notifications option in the signing & Capabilities tab in Xcode. ...

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

When working with props.data in MDBNav, learn how to set the active TAB or LINK

Utilizing ReactJS, I am incorporating MDBNav from MDBreact. This snippet demonstrates the container where props.data is defined: import React from 'react' import MiTabs from "../componentes/MiTabs"; class VpnList extends React.Component { st ...

Utilizing ES6 promises in node.js to send a null response

I'm looking for assistance on how to execute a query using ES6 native promises in node.js. The code I have below is what I've been working with: let arr= []; conn.query('select * from table1', (err, b) => { for (let i = 0; i ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Ways to prevent the selection of images

Whenever I click on the ball, a click event is triggered. However, sometimes it doesn't work because I accidentally select the image and it interrupts the click event. I attempted to remove the selectable property using the following CSS properties, ...

Navigate post Ajax call

When I make an unauthenticated GET request using AJAX, my server is supposed to redirect my application. However, when I receive the redirect (a 303 with /login.html as the location), the response tab in the Firebug console shows me the full HTML of the lo ...

Why isn't the button border displaying the color I assigned to it?

After setting a border color to my button, it's not displaying the color when I click on it. Instead, it's showing a different color. How can I resolve this issue? I need some assistance with setting the background of my button to match the imag ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Where the package.json file resides

Is there a designated location for the package.json file in a project, like within the project directory? Where should the package.json file be located in a multi-component project? What is the significance of having version 0.0.0 in th ...

Learn the best way to efficiently transfer multiple checkbox selections in a single object using AJAX

In my form, I have 4 checkboxes with unique IDs like filter_AFFILIATION_1, filter_AFFILIATION_2, and so on up to 4. My goal is to dynamically send the values of checked checkboxes to the server using an ajax call. Below is the snippet of my code: $(&a ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue: <html> <head> <script type="text/javascript" src="data.json"></script> < ...

Trigger an event when the menu is outside the viewport and then lock the menu to the top of the viewport

I am trying to create a menu element that remains fixed at the top of the browser viewport as the user scrolls, ensuring it is always visible. In my webpage layout, the menu sits below some text in the header initially. Once the user scrolls past the heade ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

Encountering a "Start script missing" error while trying to execute npm start, the problem remains even after attempting

Help, I keep encountering this issue npm ERR! missing script: start whenever I attempt to execute 'npm start' for my latest React project. I've tried searching for a solution and came across some individuals who were able to resolve it by u ...