Personalize the appearance of dynamically generated DIV elements

This script generates a random number of squares (ranging from 20 to 40) and adds text to each square. The script then calculates the width of each square so that they all fit in a single row. Here is the code snippet:

var quantity = Math.floor(Math.random() * (40 - 20 + 1)) + 20;


for (var i = 0; i < quantity; i++) {
  var elem = document.createElement("div");
  elem.className = "part";
  elem.id = 'p' + i;
  document.getElementById("scale").appendChild(elem);
}

var parts = document.getElementsByClassName("part");

for (var i = 0; i < parts.length; i++) {
  parts[i].style.fontSize = (500 / quantity) + 'px';
  parts[i].style.lineHeight = (460 / quantity) + 'px';

  parts[i].textContent = ("block #" + (i + 1));
}

for (var i = 0; i < parts.length; i++) {
  parts[i].style.height = parts[i].style.width;
}

let text = document.getElementById('txt');
text.textContent = 'BLOCKS: ' + quantity;
body {
  margin: 0;
}

#scale {
  position: absolute;
  display: table;
  width: 100%;
  top: 50%;
  transform: translateY(-100%);
  table-layout: fixed;
  border-spacing: 1px;
}

.part {
  display: table-cell;
  background-color: #a9cce3;
  padding: 3px;
  box-sizing: border-box;
  border: 1px solid black;
  border-radius: 2px;
  overflow: hidden;
}

#txt {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: 20px;
  transform: translateX(-50%);
  font-size: 18px;
  font-family: 'Arial', sans-serif;
}
<div id="scale"> </div>

<div id='txt'> </div>

The issue arises when the squares are not always perfectly square. Another problem encountered is the difficulty in setting the font size appropriately based on the square's dimensions to ensure the text fits inside them. This may not be the most efficient solution.

parts[i].style.fontSize = (500 / quantity) + 'px';
parts[i].style.lineHeight = (460 / quantity) + 'px';

Answer №1

There were a couple of issues with the code that need to be addressed:

  1. In order to access the element properly, use .clientWidth instead of style.width. It seems like you haven't set the width in your code, so this change is necessary.
  2. It's better to specify font size in percentage rather than using line-height. To center text, consider applying CSS as shown here:

Replace your code with the following:

var quantity = Math.floor(Math.random() * (40 - 20 + 1)) + 20;


for (var i = 0; i < quantity; i++) {
  var elem = document.createElement("div");
  elem.className = "part";
  elem.id = 'p' + i;
  document.getElementById("scale").appendChild(elem);
}

var parts = document.getElementsByClassName("part");

for (var i = 0; i < parts.length; i++) {
  parts[i].style.fontSize = (500 / quantity) + '%';
  parts[i].style.lineHeight = (460 / quantity) + '%';

  parts[i].textContent = ("block #" + (i + 1));
}

for (var i = 0; i < parts.length; i++) {
  parts[i].style.height = parts[i].clientWidth + "px";
}

let text = document.getElementById('txt');
text.textContent = 'BLOCKS: ' + quantity;
body {
  margin: 0;
}

#scale {
  position: absolute;
  display: table;
  width: 100%;
  top: 50%;
  transform: translateY(-100%);
  table-layout: fixed;
  border-spacing: 1px;
}

.part {
  display: table-cell;
  background-color: #a9cce3;
  padding: 3px;
  box-sizing: border-box;
  border: 1px solid black;
  border-radius: 2px;
  overflow: hidden;
  vertical-align: middle;
  text-align: center;
}

#txt {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: 20px;
  transform: translateX(-50%);
  font-size: 18px;
  font-family: 'Arial', sans-serif;
}
<div id="scale"> </div>

<div id='txt'> </div>

If you want to prevent your text from being reduced, apply the following instead:

.part {
      display: table-cell;
      background-color: #a9cce3;
      padding: 3px;
      box-sizing: border-box;
      border: 1px solid black;
      border-radius: 2px;
      overflow: hidden;
      vertical-align: middle;
      text-align: center;
       text-overflow: ellipsis;
       overflow: hidden;
      white-space: nowrap; 
    }

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

Manipulating the DOM by nesting an icon within a button element in HTML

Currently working on my todo list project and I have a question about using innerHTML. I'm curious if I can include an icon inside of a button tag like this: btn.innerHTML = '<i class="fas fa-times fa-lg"></i>'; So, wo ...

Error: Unable to access the currentTime property as it is not defined

Incorporating Videojs into my react application has presented a challenge. I am attempting to set the current time of the videojs player, but keep encountering an error that reads "cannot read property currentTime of undefined". Below is my approach: var ...

Different methods of transferring PHP post information to JavaScript

Is there a cleaner and more elegant way to pass posted PHP variables to JavaScript for manipulation, rather than using inline JavaScript? I currently have a simple PHP form that posts data to specific variables and then uses inline JavaScript to handle the ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

The jQuery fade speed effect has a limitation where it can only be utilized

When a specific link is clicked, I want a div to display with a fadeIn effect and then fadeOut when the link is clicked again. However, after the first click following an HTTP request, the fadeIn works but the fadeOut does not (the div closes though). More ...

The labels assigned to buttons will direct users to unique links specifically designated for that button

I've been working on a website to share some code I created, but my skills in HTML and CSS are not the best. Please forgive me if there are obvious mistakes. Here's the code I have so far: <!DOCTYPE html> <html> <head> ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Ensure that the div elements fully occupy the remaining space within the box

I'm looking to bring this idea to life: https://i.sstatic.net/SWytj.png Most of my work is complete, but I need the boxes to fill up all available space in the row. This is the HTML code I've used with Bootstrap. How can I achieve this? < ...

Can Bootstrap CSS take precedence over a theme's styling?

After working with various WordPress theme templates, I am now ready to take on the challenge of creating my own custom themes. One aspect I would like to incorporate is utilizing Bootstrap to ensure my website is responsive. However, I have some questions ...

Managing array elements in React: removing and duplicating items

One of my tasks is to incorporate a copy and delete button within a table. My goal is to pass the index from the map to the delete and copy onclick functions, however, I am encountering an issue where copying a row results in it having the same index as th ...

Angular Headers API Development

https://i.sstatic.net/zQzAC.jpg I've been attempting to include the X-APIKeys headers in every api call, but I'm only finding examples in curl. Here's what I've tried: var accessKey = "gdgfdgdfgdgdgfdgdfgfdgfdgdgh"; var sec ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like ...

Using .on as a substitute for live will not yield the desired results

I've been aware for some time now that the .on method is meant to replace .live, but I just can't seem to get it working. I've attempted: $(this).on('click', function(){ // Do something... }) $(this).on({ click: function ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

I'm experiencing an issue with res.redirect() as it is not directing me to the expected page. Despite no errors being shown, I am left wondering what

Despite everything working as expected, I am facing an issue with redirecting the user to a different URL after they send a message. I have tried using res.redirect from the server side in response to an AJAX POST request, but it seems like I am still on t ...

Having trouble establishing a connection with localhost at port 4445 using Nightwatch and Selenium

I am encountering an issue while trying to execute my Nightwatch script in Javascript. The error message I am receiving is: \ Connecting to localhost on port 4445... ‼ Error connecting to localhost on port 4445. × failed E ...