How can we allocate array elements dynamically within div elements to ensure that each row contains no more than N items using only HTML and JavaScript?

For instance, if N is 3 in each row, as more elements are added to the array, the number of rows will increase but each row will still have a maximum of 3 elements.

I am currently using map to generate corresponding divs for every element in the array. However, the divs are just stacking on top of each other. What I actually desire is: https://i.sstatic.net/848b1.png

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
    <br>
    <div style="display: flex;">
        <div id="deck" style="flex: 1;width:500px;height:300px;text-align:center;background-color:green;margin:0 auto;">CARDS</div>
        <div id="discard" style="flex: 0.5 1 30%;width:500px;height:300px;text-align:center;background-color:yellow;margin:0 auto;">DISCARDS</div>
    </div>
    <div id="cards" style="background-color:orange;margin:0 auto;text-align:center">XYZ</div>
    <script type="text/javascript">
        let cards = ["xf"];
        addCard("xa");
        function addCard(card){
            cards.push(card);
            document.getElementById('cards').innerHTML = cards.map(c => 
                `<div>
                <div id="${c}" onclick="selectCard(this)" style="width:50px;height:30px;text-align:center">${c}</div>
                </div>`
            ).join('')
        }
    </script>
</body>
</html>

Answer №1

Discover the wonders of CSS Grid Layout & Grid Template Columns

This piece of code could jumpstart your learning.

let cards = ["xf", "abc", "123", "45"];
addCard("xa");

function addCard(card) {
  cards.push(card);
  document.getElementById('cards').innerHTML = cards.map(c =>
    `<div>
                <div id="${c}" onclick="selectCard(this)" style="width:50px;height:30px;text-align:center;">${c}</div>
                </div>`
  ).join('')
}
#cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}
<div id="cards" style="background-color:orange;margin:0 auto;text-align:center">XYZ</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

The HTML website appears to be having trouble scrolling on Android devices, however, it functions properly on both iOS and desktop platforms

Hello everyone, I need help solving an issue with my responsive HTML website. It works perfectly on a desktop browser, but when viewed on a mobile device, it gets stuck and won't scroll. Any suggestions on what might be causing this problem? Thank you ...

What is the best way to insert a triangle shape to the bottom of a div with an opacity level set at 0.2

https://i.stack.imgur.com/sqZpM.png I've been trying to create something similar, but my triangle keeps overlapping with the background in the next section. I've already spent 3 hours on it. Any help would be greatly appreciated. Check out my c ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

What is the best method for retrieving data using Selenium when the class name may vary slightly?

Hypothetically, let's consider the following HTML code snippet displayed on a website: <div class="box"> <div class="a1"></div> <div class="a2"></div> <div class="a3" ...

Experience the Firefox nightmare with a fixed background-attachment!

I've been struggling with a puzzling issue all day, and I'm hoping that someone with more expertise can help me solve it. As I work on updating the design of my website, I've encountered what seems to be a bug specific to Firefox. I've ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Shuffle array elements in JavaScript

I need help with manipulating an array containing nested arrays. Here's an example: const arr = [[red,green],[house,roof,wall]] Is there a method to combine the nested arrays so that the output is formatted like this? red house, red roof, red wall, g ...

Can the labelDisplayedRows be disabled in the table pagination actions of Material UI?

I am currently working on customizing the table pagination actions in Material UI's table and I need to remove the labelDisplayedRows function. My goal is to only show next/previous icons in the footer without the counter (e.g., 1 of 5). I managed t ...

The JavaScript copy function is no longer functioning properly following the update to the href link

I have implemented a function for copying to clipboard as shown below: function CopyToClipboard(containerid) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); ...

The functionality of passing an ID in Bootstrap Modal is not functioning as expected

I'm facing an issue with passing an ID to my modal. My goal is to have the details of an event displayed in the modal when the corresponding link (which represents the event) is clicked. However, I'm struggling to retrieve the ID and show the ev ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

What could be the reason behind the application experiencing crashes while utilizing express-rate-limit?

I am utilizing version 6.0.1 of the express-rate-limit package to control the number of request hits, and I referenced the express-rate-limit documentation available at https://www.npmjs.com/package/express-rate-limit However, I am encountering a crash in ...

JavaScript code that formats input prices, detects any formatting errors

Before jumping to conclusions, I want to clarify that I am not inquiring about the actual process of formatting the price. Instead, I am seeking guidance on where I may be going wrong or what steps I need to take in order to achieve the desired outcome. I ...

The alignment of text in the flex column is incorrect on the right side

The flex column I created is having an issue with the arrow on the right side. It's not displaying properly and is hidden. The arrow should be similar to the one on the left and point to the left direction. I have used left: 0; for the left side and ...

Eliminate all hover functionalities from the Kendo Menu component in ASP.NET MVC

Currently, I am working on a project and utilizing the Kendo Menu. However, the package includes hover styling that I do not want to use. Is there a way to disable or remove this styling? ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

issue with brightcove player's complete event not triggering upon video replay

I have a videoplayer with an event listener added in an onTemplateReady function. Upon completion of the video, I want to replay it: videoPlayer.addEventListener(brightcove.api.events.MediaEvent.COMPLETE, completedCallback); function completedCallback(){ ...

Responsive images in CSS3/HTML5 are designed to adapt to different

I am looking to implement responsive image sizing based on the webpage size. My images come in two different sizes: <img src="images/img1.jpg" data-big="images/img1.jpg" data-small="images/img1small.jpg" alt=""></img> The data-small image has ...

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...

Finding the iframe document on Chrome

I've been attempting to dynamically adjust the height of an iframe based on its content, but I'm facing issues in the latest version of Chrome. In Chrome, 'doc is undefined' error is showing up. Surprisingly, everything works perfectl ...