Enclose specific content items with double div elements using JavaScript every nth time

I have been attempting to encapsulate two divs around every set of three content pieces received from an API call. The desired structure is as follows:

 <div class="carousel-inner">
      <div class="item carousel-item">
           <div class="row">
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          Content Here (1)              
                     </div>
                </div>
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          Content Here (2)              
                     </div>
                </div>          
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          Content Here (3)              
                     </div>
                </div>
           </div>
      </div>
      <div class="item carousel-item">
           <div class="row">
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          Content Here (4)              
                     </div>
                </div>
           </div>
      </div>
 </div>

I have spent the entire day working on this task but I am unable to achieve the desired outcome. I suspect that my approach might not be the most efficient. I am seeking guidance on what I am doing wrong and how to rectify it. Additionally, I am open to suggestions on improving the efficiency of my code. Upon retrieving 4 content pieces, the goal is to wrap every set of 3 in two divs (item carousel-item and row). However, in my current attempt, it seems to wrap 4 pieces instead of three and duplicates the 4th piece unnecessarily, leading to an extra div at the end.

Current progress:

 <div class="carousel-inner">
      <div class="item carousel-item">
           <div class="row">
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          Content Here (1)
                     </div>
                </div>
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          <div class="img-box">
                               Content Here (2)
                          </div>
                     </div>
                </div>
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          <div class="img-box">
                               Content Here (3)
                          </div>
                     </div>
                </div>
                ***this div should not be here, should have stopped at 3***
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          <div class="img-box">
                               Content Here (4)
                          </div>
                     </div>
                </div>
           </div>
      </div>
      <div class="item carousel-item">
           <div class="row">
                <div class="col-sm-4">
                     <div class="thumb-wrapper">
                          <div class="img-box">
                               Content Here (4)
                          </div>
                     </div>
                </div>
           </div>
      </div>
 </div>
 ***extra div shows up at end***
 </div>

Snippet of the code used:

 jQuery.each(ws_ftr, function(index, ftr) {
           if(index % 3 === 0){
                jQuery('.carousel-inner').append('<div class="item carousel-item active"><div class="row">');
           }
           jQuery('.row').append('<div class="col-sm-4"><div class="thumb-wrapper"><div class="img-box">Content Here</div></div></div>');
           if(index % 3 === 0){
                jQuery('.row').append('</div></div>');
           }

Answer №1

Here is a suggested code structure for creating columns:

function generateColumnLayout(data) {
  var html = '<div class="row">'; 
  //you can use another method like $.append to initiate your row
  $.each(data, function(index, item) {
    if (index % 3 == 0 && index != 0) {
      html += '</div><div class="row">'; 
     //end current row and start a new one
    }
    html += '<div class="column">' + item + '</div>'; 
    // output the content from your array
  });
  html += "</div>"; 
  //end the last row
  return html;
}

Feel free to customize this code to meet your specific requirements. Hopefully, this will be useful for you :)

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

Scrolling automatically to the first empty mandatory field with the help of AngularJS

After utilizing angular js to create a form with 7 input elements, I encountered an issue. Upon clicking submit, the form should scroll up to the first blank required field. However, it is not accurately identifying the left blank field. Any suggestions on ...

Update the text using JavaScript to modify the price range dropdown when the user clicks away

Dropdown functionality is working when selecting a price, but updating the price in the text box manually does not trigger an update. How can you implement an onblur change event for manual entry of prices? JSFiddle function nFormatter(num, digits) { ...

Storing values beyond the boundaries of an array in C++

char *variable = new char[5]; variable[10] = 'f'; How come this code does not throw an error when executed in debug mode? It leads to a crash in a release build. ...

Developing a Java application that involves reading from a file, writing to a file,

I'm currently struggling with an assignment and desperately need some assistance. I've made progress but have been stuck for several days now. The task involves students in their first year of a degree program in Irrational Studies, who take two ...

Using the ternary operator in a jQuery event

I am looking for a solution to have a button trigger different functions based on the value of a variable. It appears that the ternary operator does not work with a jQuery event trigger. var color = "blue"; $(document).ready(function(){ $('#bot ...

The getJSON API functions properly on a local machine but encounters issues when deployed on a

I have a vision to create a web application that can display the weather of any city based on user input. I've divided my project into three files - index.html for collecting user input, index2.html for retrieving and displaying the data, and a CSS fi ...

Is it possible to retrieve information from Wikipedia using Ajax?

Does anybody know of a service or api that makes it possible to fetch Wikipedia data related to a specific topic using only JavaScript? ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...

Learn how to create a smooth and consistent horizontal image slider using JavaScript to manipulate transition transforms

Does anyone know how to create a seamless sliding effect for a series of images in Vuejs? Let's say we have images 1, 2, 3, 4, and 5 When the first slide occurs, the order of images should be: 2, 3, 4, 5, 1 For the second slide: 3, 4, 5, 1, 2 And ...

Tips on preventing further input in this code - a script designed to take in a 1D array of undetermined length

I am struggling to figure out how to stop the input in my code. I have created a code that takes input from an array with integer elements. When a non-integer element is inputted, it gets ignored. However, I am unable to find a way to stop the input proces ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

Restricting the scope of ngClick in multiple instances with AngularJS

I'm working on developing a directive that can toggle an element open or closed when a specific link is clicked. The issue I'm facing is that, upon clicking one trigger, all instances are being toggled open instead of just the intended one. If y ...

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

Parsing form bodies in Express.js allows for easy extraction of data

Below is an example of a form: <!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> < ...

What techniques do Node libraries employ to achieve asynchronous execution in a professional manner?

After researching how Node Bcrypt accomplishes asynchronous execution with the following code: bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. }); I am curious about how they manage to perform com ...

The Bootstrap carousel indicators are not automatically switching because they are placed outside of the main div

I have integrated the latest Bootstrap framework into my website, featuring a visually appealing carousel. The unique aspect of my carousel design is that the indicators are positioned outside the main carousel div. Here is a snippet of my carousel code: ...

What is the process of adding information to a JSON file?

I'm looking to store my data in an external JSON file and have it update the list when the page is reloaded. Can anyone assist with this? Below is my code: $scope.addUser = function() { var user = { id: null, login: '', ...

Is it possible in Javascript to verify if a different script has been triggered?

I recently created a pop-out menu for a website using HTML and Javascript. The menu currently has a button that opens a div container with a close button inside it. While the buttons are functioning properly in hiding the div, the elements within the div d ...

What is the best way to measure the timing of consecutive events within a web browser, utilizing JavaScript within an HTML script tag?

Currently delving into the realm of JavaScript, transitioning from a Java/Clojure background, I am attempting to implement a basic thread-sleep feature that will display lines of text on the screen at one second intervals. Initially, I considered using t ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...