Should we eliminate the overflow from multiple divs in the container, rather than just hiding it, or should we limit the overflow to

Looking for a solution to create a background that adjusts the number of square divs based on the size of the container, which changes when resizing the window.

I tried referencing examples from this post here to add the divs. However, the issue arises when resizing the screen as it keeps multiplying the number of divs. Is there a way to limit the squares to fit within the container size or handle the overflow?

(Avoiding a simple css overflow:hidden solution to prevent an excessive multiplication of divs.) As I am new to JavaScript, any guidance would be greatly appreciated!

let contain = document.getElementById("squareContain");
let width = contain.offsetWidth;
let height = contain.offsetHeight;
var containerArea = width * height;
var canAdd = Math.floor(containerArea/1600); //For 40px x 40px squares

function multiplyNode(node, count, deep) {
    for (var i = 0, copy; i < count - 1; i++) {
        copy = node.cloneNode(deep);
        node.parentNode.insertBefore(copy, node);
    }
}

$(window).on("resize", function(){
    multiplyNode(document.querySelector('.square'), canAdd, false);
}).resize();

Edit jsfiddle

Answer №1

It is important to dynamically recalculate the number of squares that fit within a container whenever the window size changes. Here's an example code snippet demonstrating how this can be achieved:

let contain = document.getElementById("squareContain");
function calculateSquareCount()
{
  let square = contain.children[0],
      cWidth = contain.offsetWidth,
      cHeight = contain.offsetHeight,
      sWidth = square.offsetWidth,
      sHeight = square.offsetHeight;

  return Math.floor(cWidth / sWidth) * Math.floor(cHeight / sHeight);
}
function adjustSquareNodes(node, count, deep) {
    if (contain.children.length == count)
      return;

    if (contain.children.length < count)
    {
      for (var i = 0, copy; i < count - 1; i++) {
          copy = node.cloneNode(deep);
          node.parentNode.insertBefore(copy, node);
      }
    }
    else
    {
      while(contain.children.length > count)
      {
        contain.removeChild(contain.children[contain.children.length -1]);
      }
    }
}

$(window).on("resize", function(){
  adjustSquareNodes(contain.querySelector('.square'), calculateSquareCount(), false);
}).resize();
.square_container{
  background-color: #ccc;
  position: fixed;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-content: start;
  flex-wrap: wrap;
  margin: 0 auto;
  padding: 0 auto;
}
.square{
  width: 40px;
  height: 40px;
  background-color: blue;
  border: 1px solid red;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="squareContain" class="square_container">
    <div class="square"></div><!--...etc...-->
</div>

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

Traversing the nested arrays, processing column by column

Below is an array of subarrays const array = [ [0, 1, 2, 3], // Going from top to bottom? [4, 5, 6, 7, 8, 9], // | [10, 11, 12, 13, 14], // | [15, 16, 17, 18, 19], // | ] // V My goal is to achieve the fol ...

Is there a way to automatically transfer the store's order value to my payment gateway's checkout process during the checkout process?

I am facing an issue with integrating the Razorpay payment gateway into my online store built on ecwid. The process involves decrypting order details from the store, sending them to the payment gateway for processing, and redirecting the customer back to t ...

What is the procedure for initiating a POST request when the payload is ready for submission?

After a successful payment, my success page is displayed with a URL that includes a query parameter. I want to make a POST request to my API endpoint when the page loads, but I'm encountering an issue where the first POST request is empty (router.quer ...

CSS3 filter: image stacking over one another

I've encountered a minor issue with my CSS code. Whenever I apply filter:gray; to my CSS stylesheet, the black/white images overlap the menu. However, when there is no filter effect on the pictures, the menu behaves as intended. CSS: img.images { ...

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...

Steps for importing an image into a phpMyAdmin database and associating it with a particular username

My goal is to upload images to a phpmyadmin database and associate them with specific usernames. I then want to retrieve these images and display them on an HTML page using jQuery, AJAX, PHP, and JavaScript. As a beginner, I am looking for the simplest way ...

Achieving successful ratings for various items

Struggling to implement star ratings for multiple items, my code seems to be mixing up the ratings. Here's a snippet of the HTML: <div class="thumbnail"> <img src="https://images.unsplash.com/photo-147031 ...

The React app hosted on Firebase displays a message saying "please activate JavaScript to run this application"

I created a web app using React that is hosted on Firebase Hosting, with a backend server utilizing Express and Cloud Functions. You can access the website here: The landing, login, and signup pages are functioning properly. However, when trying to acces ...

What is the reason for requiring this to be passed as an Array instead of a String?

I'm currently learning node.js through a tutorial in a book titled Node Web Developments. Issue: I am struggling with understanding why an array [] is being passed as the 3rd argument from mult-node.js to the required function htutil.page(), instead ...

Learn how to send information to a form and receive a response when a key is pressed, either up or down, by

Can you help with fetching data and passing it into a form to respond to customer names on keyup or keydown using JSON and PHP? <?php $conn = new mysqli("localhost", 'root', "", "laravel"); $query = mysqli_query($conn,"select * from customers ...

Incorporate additional information into the current data series within Lightning Chart

In my React JS application, I have successfully used a point series to create a chart displaying data. However, I am now looking to bind real-time data to the chart. For example, when the chart initially loads with 10 points, I want to continuously receiv ...

Using JQuery with the latest version of Google Sites is a game-ch

My coding knowledge is very limited, especially beyond VBA. I've hit a roadblock and it seems like I'm overlooking something obvious. What I'm attempting to accomplish: I need this code to be integrated into a New Google Sites page (which h ...

Experiencing issues with archiving files in PHP and receiving a 'zipArchive::close() Read Error: no such file or directory in c:/' error message?

When using PHP to download multiple files as a zip folder, the code below is giving me an error message: "zipArchive::close() Read error: no such file or directory in C:// path" I have added an HTML button that, when clicked, retrieves the id of the row t ...

The Angular-ui typeahead feature is delivering accurate results when the backspace key is pressed

I've been using Angular-UI typeahead and it's been working fine, but I've noticed a strange behavior when I hit the backspace key - it gives the correct results. For example, if I type sector 4 The result is Sector 1 Sector 2 ...

Interacting with Django backend via AJAX to trigger Python functions using jQuery/AJAX

Currently, I am developing a small website using Django. Within this project, there are DateTime fields that need to be handled. My intention is to utilize ajax by implementing another button to establish the UTC date while taking into consideration sola ...

The selected data is not being displayed

My input field is not displaying anything. Below is the script function in my view: <script> var Features = []; function LoadFeatures(element) { if(Features.length === 0) { $.ajax({ url:'@Url.Action("GetFeatures"," ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...

Tips for utilizing an array within React and transforming it into a component

I've developed a website that pulls data from a SQL database I created, containing details such as name, address, and occupation of individuals. I successfully managed to showcase this information on the webpage by structuring an array and inserting t ...

Issue with confirming deletion of tabulated records

HTML Code: <td>random_data_1</td><td><button id="random_data_1"></button></td> <td>random_data_2</td><td><button id="random_data_2"></button></td> <td>random_data_3</td ...

Error: Discord API experienced an Invalid Form Body error

I've tried multiple approaches, but I'm still unable to resolve the issue with this code. Any assistance would be greatly appreciated. CODE: client.on("messageCreate", async message => { if (message.author.bot || !message.guild) return; if (m ...