Creating interactive HTML cards by dynamically generating them from a Javascript array and Bootstrap, organizing them into distinct rows and columns

I need assistance in structuring my Team section with multiple rows, each containing 5 cards. I have a list of team members that I want to display in this format using a single array and loop. However, I am struggling to figure out how to automatically create new rows when one row is filled with 5 cards.

Currently, I manually created 3 different arrays for 3 rows, but the goal is to achieve this layout efficiently using a Single Array and Single Loop.

const teamDataOne = [
  {
    img: "img/team/man.png",
    name: "Bimal Timilsina",
    position: "Web Designer",
    facebook: "https://facebook.com/",
    email: "mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13607c7e767c7d7653747e727a7f3d707c7e">[email protected]</a>"
  },
  // Additional team members...
];

const container = document.getElementById("teamRowOne");

teamDataOne.forEach(result => {
  const content = `
    <div class="col-md-2 shadow p-3 mb-5 bg-white rounded ">
        <img src="${result.img}" height="150" width="150" alt="name">
        <h4>${result.name}</h4>
        <h6>${result.position}</h6>
        <div class="border-bottom"></div>
        <a href="${
          result.facebook
        }" target="_blank" class="btn-social btn-facebook"><i class="fa fa-facebook"></i></a>
        <a href="${
          result.email
        }" target="_blank" class="btn-social btn-email"><i class="fa fa-envelope"></i></a>
        </div>
    `;

  container.innerHTML += content;
});

Below is a snippet of the HTML code:

<div class="row justify-content-around wow zoomIn" id="teamRowOne">
      </div>

The desired outcome is to have only five cards aligned in each row.

Answer №1

There are countless methods to achieve this task, but I will provide an example utilizing the modulo operator. You can accomplish it within a single loop like so:

// Stop using 'row' as a container and utilize the parent element instead
var container = document.getElementById("row-container");
var content="";    
teamData.forEach(function(result,i){
  if(i == 0){
    // Add the start of a row 
    content+= '<div class="row">'
  }
  // Add content
  content += '<div class="col....'

  if(i!=0 && i%5 == 0){

    // Close the current row and start a new one every 5 elements
    content += '</div><div class="row">'
  }

});
// Don't forget to close the last row after looping through all elements 
content += '</div>'
container.innerHTML += content;

(This is pseudo code that can be adjusted according to your requirements)

Answer №2

When using bootstrap grid classes row and col, a column created with col-md-2 will result in 6 partitions within a single row. This may cause 6 cards to be displayed in one row if more than 5 team members are added to the array.

While there is no specific class to divide the row into 5 partitions, you can add a small margin to achieve a layout of five cards per row. One solution is to use the m-2 class which adds a margin of 2px.

To implement this, simply add the class within the loop where you are creating the column:

<div class="col-md-2 m-2 shadow p-3 mb-5 bg-white rounded ">

Give it a try and see if it produces the desired outcome for your design.

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

Is there a way to showcase the present weather conditions using simpleweather.js in plain text format?

I have integrated the weather.js library into my HTML file by adding the necessary imports: <script src="js/current.js"></script> <script src="js/sugar.min.js"></script> <script src="js/weather.js"></script> <script ...

Fixing the issue of "additional space" in the Login Card with Bootstrap 5

I am currently working on a basic login form using bootstrap and encountering an issue, below is the code snippet: <div class="container"> <div class="row justify-content-center no-gutters" style="padding-top:150px ...

Error message: `String not found in List.contains()`

Struggling to comprehend the functionality of the List.contains() method in this scenario, strAttributeList - List of chosen attributes subscriptionAttrList- List of all attributes I need to verify that each selected attribute in strAttributeList is pres ...

How to access an HTML element in TypeScript similar to the use of the dollar sign ($) in JavaScript

In my current web project, I have implemented a parallax effect using JavaScript. The code selects an element with the class ".parallax" and calls the method "parallax()". This is essential for the parallax effect to function properly. $('.parallax&a ...

Experiencing an excessive amount of re-renders in React due to useState

In this scenario, the user is expected to press the correct letter on the keyboard (which is the first letter of the bird's name) in order to delete the first bird's name from the birds array. This process repeats until the array is empty. Howeve ...

Creating new components within A-frame

I've been attempting to implement the bubble function into my scene to generate a sphere, but unfortunately nothing is showing up. Even when I try creating a sphere without using the bubble function, it still doesn't appear in the scene. func ...

The horizontal navigation bar will not extend the entire length of the page

I'm facing an issue with my horizontal navigation bar as it doesn't span the entire screen. I need help figuring out how to make it full-width. You can see what I mean here. Additionally, once the navigation bar spans the screen, I want the image ...

Woops! Looks like there's an issue - the property 'url' is not defined and cannot be

I am currently working on fetching data from a REST API using angular2, and everything seems to be going smoothly. However, I have encountered an error that only appears in the console when calling {{content.img.url}}. Interestingly, the code executes fine ...

Differences in Angular.js/jQuery html string parsing between versions 1.9.1 and 1.8.3

When attempting to use angular.element(stringWithHtmlStructure);, an error is thrown: Error: Syntax error, unrecognized expression: <div id="foo">bar</div> This issue occurs in jQuery 1.9.1 but not in 1.8.3. Is this a bug or a deliberate sec ...

What steps should be taken to execute a function based on whether a user grants or denies access to their "Physical Location"?

The functionality of my app relies on jQuery mobile and geolocation services. Once the app requests the user's location, a prompt appears in the (Chrome) browser: Example.com is requesting to access your physical location [allow] [deny] My object ...

Changing the depth buffer in a Three.js Shader Material

While working with Three js, I have implemented a vertex shader to animate a large geometry. Additionally, I have incorporated a Depth of Field effect into the output. However, I am encountering an issue where the Depth of Field effect does not seem to re ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Looking for Assistance with Creating a Non-Adhesive Footer in CSS?

My goal is to have the footer remain at the bottom of the page, which I achieved using the following CSS: position: absolute; bottom: 0px; While this code does bring the footer to the bottom as desired, the issue arises when the window is resized to a sm ...

Sending a php DateTime object to javascript using Ajax

I sent a php datetime object via ajax. Now, I am able to access it in javascript like this: {"timezone":{"name":"Asia\/Tokyo","location":{"country_code":"JP","latitude":35.65231,"longitude":139.74232,"comments":""}},"offset":32400,"timestamp":147265 ...

How to add dimensions to a background image using CSS3

I would like the background image to have a size of 636px by 1140px instead of applying it to the div element directly. This is because I want to avoid scrollbars due to the height of the div. When I specify the width and height for the parent div, the ba ...

In Python, make sure to reference each individual JSON element within an array

I need help with parsing JSON objects stored in an array. How can I efficiently extract each object from the array? For instance, I am looking to extract and parse {"occurrences":"1","post_title":"Test 5","ID":"16"} and then submit it as a body to an API. ...

Verifying a user's initial visit status using COOKIES in a Servlet

Is there a method to determine if a user is visiting a page for the first time using SERVLET and cookies, without utilizing sessions? I understand how to accomplish this with sessions, but I am specifically looking for a solution that involves only cooki ...

text breaks free from the flex container when zooming in

Hi, I am attempting to design a user card-type div that includes images on the left and the username on the right. I have managed to create the layout, but when zooming in, the text is overflowing and escaping the flex container. Here is my code snippet. Y ...

PHP encounters difficulty in forming and allocating an array

Can PHP store an array where a string was previously stored? echo "valuebefore: ".$_SESSION['REQUEST_TOKEN'][TL_MODE]; $_SESSION['REQUEST_TOKEN'][TL_MODE] = "somestring"; echo "typebefore: ".gettype($_SESSION['REQUEST_TOKEN' ...

Cookie Multitree: An Innovative JsTree Solution

Hello everyone, I am currently using jstree and have come across a couple of issues with having multiple trees on the same page. Here are my two problems: 1) I am looking to implement cookies to keep track of which nodes are open in each tree. I attempted ...