Home > Net >  Dynamically add and close DIV to group of 3 cards
Dynamically add and close DIV to group of 3 cards

Time:07-06

I'm using bootstrap 4 and receive lines of data like below from the DB/backend. I'm wondering if there's a way to dynamically wrap each group of 3 with <div >...</div> for big screen size (>992), and wrap each group of 2 with the same <div >...</div> for smaller screen size.

What received

  <div >...</div>
  <div >...</div>
  <div >...</div>
  <div >...</div>
  <div >...</div>
  <div >...</div>

Desired Ouput for Big Screen (>=992)

<div >
  <div >...</div>
  <div >...</div>
  <div >...</div>
</div>

<div >
  <div >...</div>
  <div >...</div>
  <div >...</div>
</div>

Desired Ouput for Smaller Screen (<992)

<div >
  <div >...</div>
  <div >...</div>
</div>

<div >
  <div >...</div>
  <div >...</div>
</div>

<div >
  <div >...</div>
  <div >...</div>
</div>

CodePudding user response:

You can use

Note: Run snippet in "Full page" mode.

function columnsWrapper(cols) {
  let $cardHolders = $('.cardHolder').unwrap('.row');

  // wrap
  for (let i = 0; i < $cardHolders.length; i  = cols) {
    let $slice = $cardHolders.slice(i, i   cols);
    $slice.wrapAll('<div  />')
  }
}

function displayColumns() {
  if ($(window).width() > 992) {
    columnsWrapper(3);
  } else {
    columnsWrapper(2);
  }
}

displayColumns();
$(window).resize(() => displayColumns());
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div  id="container">
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
  <div >9</div>
</div>

  • Related