Creating multiple div columns dynamically with jQuery

Check out the code snippet below:

<div id="container">
    <div class="b">test1</div>
    <div class="b">test2</div>
    <div class="b">test3</div>
    <div class="b">test4</div>
    <div class="b">test5</div>
    <div class="b">test6</div>
</div>

CSS

.b {
    display:inline-block;
    position: relative;
    margin: 2px;
    float:left;
    width: calc(16.7% - 10px);
    height:400px;
    background-color: white;
    border: 1px solid black;
}

http://jsfiddle.net/329vcLLc/ works perfectly, displaying 5 columns as desired.

I need to loop through an array to create div elements based on the array length. I was thinking of using the append() function. What do you suggest? Also, how can I dynamically set the width property for each div based on the number of columns?

Any suggestions or ideas?

Answer №1

I'm not entirely sure about the factors influencing the number of divs, but if you want to create a specific quantity of divs, you can follow this approach:

var n=8;
var $cont=$('#container');
for(var i=1; i<=n; i++)
{
    var d=$('<div>').addClass('b').html('test '+(i)).css('width', 'calc('+(100/n)+'% - 10px)');
    $cont.append(d);
}
.b {
    display:inline-block;
    position: relative;
    margin: 2px;
    float:left;
    height:400px;
    background-color: white;
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"> 
</div>

Answer №2

To implement the given CSS, you can follow these steps:

var divs = ['a','b','c','d','e', 'f', 'g'];
var con_width = parseInt($('#container').width()); //retrieve container width
var width = (con_width / divs.length) - 10; //divide by number of divs and adjust for fitting

$.each(divs, function(index, value){
    var div = $('<div />').addClass('b').text(value).css('width', width + 'px'); 
    $('#container').append(div); 
});

Check out the demo here

Additional Resources:

.each() method guide

.width() method documentation

.css() method information

.addClass() method details

.text() method explanation

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

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Validation of form fields appears to be disregarded

I seem to have overlooked a simple issue with this form field validation method. It has worked effectively for me in the past, but now, despite checking all file paths, every time I submit the form, it sends an email regardless of the field content. You c ...

Vue Single Page Application - invoking methods across all components

I am currently developing a notification feature that can be triggered from any component. It utilizes a straightforward Vuetify v-snackbar. Within App.vue <router-view :key="$route.fullPath"></router-view> <v-snackbar :valu ...

.displaying a grid of div elements is not functioning as expected

On a single page, there is a grid of Divs (2 by 3) with a menu (<li> in <lu>) positioned to the left of the grid. Each menu section contains its own grid of divs, all enclosed within one main div to facilitate manipulation. Menu Sections: < ...

Resizing Images Responsively Using Bootstrap

I'm working on specifying image sizes for different screen sizes. I'm wondering if there are any specific Bootstrap classes that only work at certain screen sizes. If so, it would be great because then I could use something like <img class = " ...

The form-group nested within a form-horizontal is exceeding the boundaries of the preceding form-group

I am currently utilizing Bootstrap 3.3.6 and have a basic form enclosed in a panel: https://i.stack.imgur.com/UOFI6.png Although it is quite simple, the alignment of the "Post" button is not displaying properly. Here is the HTML code for the form: < ...

Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows: <div class="row"> <div class="col-md-12"> <div id="calendar"></div> <table id="report" class="table"> <thead> <tr> <th> ...

The functionality of $http get parameters is malfunctioning

Is there a reason why this code snippet is not functioning properly? $http .get('accept.php', { source: link, category_id: category }) .success(function (data, status) { $scope.info_show = data }); On the ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

Angular2: Issue encountered while processing click event

When I click a button on my client application, it sends a request to the server I created using Express. The request handler in the server simply logs 'Delete from server' every time the button is clicked. I am encountering these errors when cl ...

Extract JSON from the response data in the success callback of a JQuery.ajax

I've encountered an issue with retrieving the contents of a JSON object from a JQuery.ajax call. Here is my code: $('#Search').click(function () { var query = $('#query').valueOf(); $.ajax({ url: '/Products/Se ...

Having trouble adding your own styling to bootstrap-4 using a custom CSS file?

Here is the code I used to connect my two stylesheets, with the custom css file being linked second as per what I believe is the correct way to do it. <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href=" ...

What is the reason for the Client Height value not affecting other elements?

I'm trying to set the spacing of my sidebar from the top equal to the height of the header. However, when I use clientHeight in JavaScript to get the height and then try to apply it to other elements using marginTop or top values (with position includ ...

How to dynamically load bootstrap-multiselect within a loop in a vueJs application

I am attempting to dynamically load bootstrap-multiselect in a loop using VueJs. My desired implementation looks something like this: <div class="col-xs-6 col-sm-4 mb-1" v-for="params in param"> <select class="mult" multiple="multiple"> ...

Using Cypress for drag and drop functionality within shadow DOM

I encountered an issue in cypress with drag and drop functionality within the shadow dom. My attempt to perform a drag event is as follows: cy.get(".shadow-app>div>div:nth-child(1)", { includeShadowDom: true }).trigger("dragstart&q ...

What causes a stack trace to be logged alongside a rejected Promise in Node version 7.2.0?

After executing this code in Node 7.2.0: let prms = Promise.reject(new Error('error')); prms.catch(() => {}); console.log(prms); I anticipated Promise {<rejected> Error: error} to be displayed on the console, however I was instead pre ...

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...

Ways to access dropdown menu without causing header to move using jQuery

Greetings everyone, I am currently working on a dropdown language selection feature for my website. The issue I am facing is that when I click on the language dropdown in the header, it causes the height of the header to shift. $('.language- ...

Adding a distinct key and its corresponding value to an array in Vue for a unique

I am attempting to add key-value pairs into an array while ensuring their uniqueness. Currently, I am trying the following approach: for (const [key, value] of Object.entries(check)) { console.log(`${key}: ${value}`); this.inputFields. ...

Struggling to get getInitialProps working in dynamic routes with Next.js?

I am encountering an issue. The return value from the getInitialProps function is not being passed to the parent component. However, when I console.log the values inside the getInitialProps function, they appear to be correct. Here is the code snippet: i ...