Tips for dynamically adding divs inside a parent div until its width and height are fully utilized

Background: At this moment, I am in the process of creating a webpage where users will input tile width & height along with floor width & height. The aim is to calculate the area of the floor, with tiles measured in inches and the floor input measured in feet.

Technical Info: To carry out the calculations, I have configured 1 foot as equivalent to 60 pixels and 1 inch as equal to 5 pixels.

Current Challenge: Currently, my stumbling block lies in generating all the tile elements (child divs) within the designated area (parent div). I am currently relying on a simple for loop for this task.

Here's a preview of the current output...

https://i.sstatic.net/Kdspj.jpg

Objective: My goal is to implement a feature where upon clicking the Calculate Button, the user can visualize the floor design. Details such as coloring and patterns will be added at a later stage.

The expected output should resemble this image (please disregard any misalignments in the borders as it was created using Windows Paint):

https://i.sstatic.net/XyJYw.jpg

Code:

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) { 
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());
                
                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));


                for (let r = 0; r<10  ; r++) {
                    // const element = array[r];
                    $("#area").append("<div id='tile_"+r+"' style='width:"+((inch * tileW))+"px; height:"+((inch * tileH))+"px;' class='border_color'> </div>");
                    
                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 1px solid; /* use instead of border */
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">
    <p>Tile Height (inches): </p><input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">
    <br>
    <p>Area Width (foot): </p><input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">
    <p>Area Height (foot): </p><input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>
        
    

    <div id="area">

    </div>

External Link to Fiddle: https://jsfiddle.net/22gLkguL/

I've attempted to accomplish this task without success... Could someone lend me their expertise or steer me in the right direction?

Answer №1

Utilize the CSS properties display: flex and flex-wrap: wrap

#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

Then, determine the maximum number of div elements that can fill each side (width or height) efficiently.

$(document).ready(function() {
  $("#btnCalculate").click(function(e) {
    e.preventDefault();

    $("#area").empty();

    const foot = 60,
      inch = 5;

    let tileW = parseFloat($("#tileWidth").val());
    let tileH = parseFloat($("#tileHeight").val());

    let areaW = parseFloat($("#areaWidth").val());
    let areaH = parseFloat($("#areaHeight").val());
    
    var areaHeight = (foot * areaH)
    var areaWidth = (foot * areaW)
    var divHeight = (inch * tileH)
    var divWidth = (inch * tileW)
    
    $("#area").css("height", areaHeight);
    $("#area").css("width", areaWidth);

    var nums = Math.floor(areaWidth/divWidth) * Math.floor(areaHeight/divHeight)

    for (let r = 0; r < nums; r++) {
      var $div = $('<div>', {
        id: 'tile_' + r,
        class: 'border_color',
        height: divHeight,
        width: divWidth,
      })
      $("#area").append($div);

    }
  });
});
#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.border_color {
  outline: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id="tileWidth" placeholder="Tile Width" value="6">
<p>Tile Height (inches): </p><input type="numbers" id="tileHeight" placeholder="Tile Height" value="4">
<br>
<p>Area Width (foot): </p><input type="numbers" id="areaWidth" placeholder="Area Width" value="11.5">
<p>Area Height (foot): </p><input type="numbers" id="areaHeight" placeholder="Area Height" value="6.5">
<button id="btnCalculate">Calculate</button>



<div id="area">

</div>

Answer №2

To create an area element, apply the following CSS properties: display: flex; flex-wrap: wrap.

Next, determine the number of tiles needed using the formula:

(areaWidthInPixels / tileWidthinPixels) * (areaHeightInPixels / tileHeightinPixels)

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) { 
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());
                
                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));
                
                let noOfTiles = Math.floor( ((foot * areaW)/(inch * tileW)) )* Math.floor( ((foot * areaH)/(inch * tileH)) );

                alert("noOf Tiles :: " + noOfTiles);
                
                for (let r = 1; r <= noOfTiles  ; r++) {
                    var bgColor = r % 2 == 0 ? "red" : "green";
                    $("#area").append("<div id='tile_"+r+"' style='width:"+((inch * tileW))+"px; height:"+((inch * tileH))+"px; background-color: " + bgColor + "'' class='border_color'> </div>");
                    
                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
            display: flex;
            flex-wrap: wrap;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 0px solid; /* use instead of border */
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">
    <p>Tile Height (inches): </p><input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">
    <br>
    <p>Area Width (foot): </p><input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">
    <p>Area Height (foot): </p><input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>
        
    

    <div id="area">

    </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

Should we pause JQUERY AJAX to prioritize usability, or only when absolutely necessary?

I am struggling with my LoadingStatus Function, which has two options: SHOW and HIDE. When a JQUERY POST is made, the Show option triggers to display, while the HIDE option occurs after the RESPONSE comes back. The problem I'm encountering is that s ...

Coordinates of HTML elements corners after rotation

Seeking to obtain the XY coordinates of an HTML element in order to accurately calculate the physical distance, in pixels, from the corners of a rotated element relative to another element. In this code snippet, I am attempting to determine the distance f ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

Encountering the 'unsupported_grant_type' error while attempting to retrieve an access token from the Discord API

Having trouble implementing Discord login on my website. When trying to exchange the code for an access token from https://discord.com/api/oauth2/token, I keep getting the error { error: 'unsupported_grant_type' }. This is my code: const ...

Issue with Django where only one out of six buttons is assigned the jquery popup window

Currently developing a cookbook website and facing a challenge. Attempting to integrate django pagination with a sleek popup jquery plugin found at this link: Encountering an issue where only the first recipe button activates the popup window, displaying ...

Anticipated outcome for absent callbacks in module API implementation

I am seeking advice on the expected behavior when developing a Node module API. It is becoming complicated in my module implementation to check if the caller has provided a callback before calling it. I am starting to believe that it may be the user's ...

Moving an object from one container to another using the draggable feature

I have successfully implemented a feature that allows an element to be dragged from one container to another. However, a new issue has arisen. Once the element is dropped into the second container, it is no longer draggable within the same container. $( ...

Creating an indentation on one side of a div using CSS for a visually appealing effect

https://i.stack.imgur.com/io6m0.jpg I'm in the process of trying to create two shapes using CSS. I've been able to almost achieve the first shape on the left, but it extends out too far. As for the second shape, I'm having difficulties cre ...

Issue with SVG animation causing unnecessary duplication of circle shapes when utilizing animateMotion

I have implemented animateMotion to create an animation along a path. Below is the code snippet that demonstrates this: <!DOCTYPE html> <html> <head> <title>Example Of Many Things!</title> </head> <body> ...

Place the blockquote in the middle, but maintain the text's alignment to

I recently designed a webpage using Bootstrap and CSS. My main goal is to have my two blockquotes centered on the page while keeping the text left-aligned (which is the default behavior for the selected classes in Bootstrap). To see the full code, take a ...

The progress bar in Java Script is static and cannot be customized to change colors

Trying to use HTML for image uploads and I've created Java code to monitor the progress of the upload. However, I'm facing an issue where I cannot change the color of the progress loading bar. Below is the code I am currently using for uploading ...

VueJS is unable to access an array

Unable to access an array in Vue.js. console.log(this.ref_number_response[0]); When I try to access the array, it shows undefined. I'm puzzled by this... data(){ return{ ref_number_response: [], } }, methods:{ che ...

Tailored class designed to handle navigation between preceding and subsequent items

I am in the process of developing a PHP page that includes fields for First Name, Last Name, Address, ZIP, and various others. My goal is to incorporate an 'Add More' button, a 'Previous' button, and a 'Save' button into the p ...

Sass fails to import the theme for the angular material checkbox

I'm facing an issue where, despite specifying imports in my SCSS file and setting up a custom theme, the checkbox styles are not visible except for those related to typography. This is what my SCSS file looks like: @import "~bootstrap/scss/bootstrap ...

The dimensions of the image are distorted when viewing the website on a mobile device

Having an issue with displaying an image behind text on a mobile device. The website looks fine on desktop and even in mobile mode from the console, but once deployed and viewed on an actual mobile device, the image becomes stretched out. Tried setting wi ...

Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' lo ...

Unable to retrieve the variable within the event handler

Currently, I am working on managing a simple form using JQuery for DOM manipulation. Below is the code snippet: var username = $('#username').val(); var email = $('#email').val(); var pass = $('#pass').val(); $('#signup ...

Is the default choice for the dropdown list set to Razor?

I am encountering an issue with a Razor declaration that results in a duplicated element in a drop-down menu. The code in question is as follows: @Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole a ...

Opacity of absolutely positioned elements

I am currently working on creating a popup box that will gray out the surrounding area. The problem I'm facing is that the opacity of the shadow div seems to be overriding that of the popup. I have tried changing the position from absolute to fixed an ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...