What is the best way to incorporate the class "row" in jQuery when a bootstrap column reaches a total

In my jQuery code, I am appending images inside a div container. I need help adding a div class row when the column count reaches 12.

Any suggestions would be greatly appreciated. Thank you in advance!

for (var i = 0, j = result.images.length; i < j; i++){
    $("#imageContent").append("<div class='col-md-3'><img src='storage/uploaded/" + result.images[i].name + "' class='img-responsive img-thumbnail'></div>");
}

Here is my current div structure:

<div class="container" id="imageContent" style="display: block;">

</div>

Current output:

<div class="container" id="imageContent" style="display: block;">
    ... (images here)
</div>

I want to add a Div class row when the column reaches 12 for the expected output:

<div class="container" id="imageContent" style="display: block;">
  <div class="row">
    ... (first set of images here)
  </div>
  <div class="row">
    ... (second set of images here)
  </div>
</div>

Answer №1

Here is a method you can use:

for (var i = 0, j = result.images.length; i < j; i++){

    if(i==0 || i%4 == 0)
    {
        var appendEl = $("<div class='row'></div>").appendTo("#imageContent");
    }
    $("<div class='col-md-3'><img src='storage/uploaded/" + result.images[i].name  + "' class='img-responsive img-thumbnail'></div>").appendTo(appendEl);
}

For more details, please refer to this js fiddle https://jsfiddle.net/9Lrg2ecq/

To see the updated version, take a look at this screenshot https://ibb.co/fzcR6Q

Answer №2

A helpful tip is to develop a function that can track how many instances of the col-md-3 class are present in the last child of the final row within your container.

For example:

$('.container .row:last-child .col-md-4').length;

If there happen to be more than 4 occurrences of the col-md-3 class, then go ahead and create a new .row element and rerun this function. But if not, simply include

$("#imageContent").append("<div class='col-md-3'>...");
at the end of the last row child :-)

Answer №3

One way to accomplish this is by using the wrapAll() function in jQuery. More information can be found at http://api.jquery.com/wrapall/

Although I haven't been able to test it, your code should look something like this:

for (var x = 0, y = result.images.length; x < y; x++) {
            if (x % 4 == 0) {
                $("#imageContent").append("<div class='col-md-3'><img src='storage/uploaded/" + result.images[x].name + "' class='img-responsive img-thumbnail'></div>");
                $(".col-md-3").wrapAll("<div class='row' />");
            }

            else {
                $("#imageContent").append("<div class='col-md-3'><img src='storage/uploaded/" + result.images[x].name + "' class='img-responsive img-thumbnail'></div>");
            }
        }

Answer №4

Check out this code snippet, it might be able to assist you:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example using Bootstrap</title>
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container-fluid">

  <p>Try resizing the browser window to see the effect.</p>
  <div id="new_row">
    <div class="row">
      <div class="col-md-3 col-sm-3 col-xs-3" style="background-color:yellow;">
        Lorem ipsum dolor sit amet
      </div>
      <div class="col-md-3 col-sm-3 col-xs-3" style="background-color:green;">
        Lorem ipsum dolor sit amet
      </div> 
      <div class="col-md-3 col-sm-3 col-xs-3" style="background-color:orange;">
        Lorem ipsum dolor sit amet
      </div> 
      <div class="col-md-3 col-sm-3 col-xs-3" style="background-color:red;">
        Lorem ipsum dolor sit amet
      </div> 
    </div>
  </div>
</div>
<script>
$( document ).ready(function() { 

for (var i = 0, j = 10; i < j; i++){

if(i==0 || i%4 == 0)
{
 var appendEl = $("<div class='row'></div>").appendTo("#new_row");
}
$("</div><div class='col-md-3 col-sm-3 col-xs-3'><img src='storage/uploaded/" + i + "' class='img-responsive img-thumbnail'></div>").appendTo(appendEl);
}
});
</script>
</body>
</html>

Answer №5

To achieve a "paginator-like" behavior, you will need to implement another loop that surrounds your current one. The initial loop will calculate the number of rows needed (the total number of images divided by 4 since there are 4 columns in each row), while the inner loop will run 4 times to populate each row.

for (index = 0 ; index < images.length / 4 ; index++) {
    var row = document.createElement('div');
    row.className="row";
    for (j = index * 4 ; j < (index * 4) + 4 ; j++) {
        var col = document.createElement('div');
        $(col).addClass("col-md-4");
        $(col).html('<img src="' + images[j] + '"/>');
        $(row).append(col);
    }
    $('body').append(row);
}

Answer №6

       <div class="container">
            <?php   $counter =0;
                    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
                    $args = array(
                      'posts_per_page' => 4,
                      'paged' => $paged
                    );
                    $custom_query = new WP_Query( $args );
                       while($custom_query->have_posts()) :
                          $custom_query->the_post();
            ?>
            <?php
                    if ( has_post_thumbnail()) {
                        $post_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
                        }
            ?>
            <div class="col-md-4 col-sm-4">
                <div class="latest-post">
                    <a href="<?php the_permalink(); ?>"><img src="<?php echo $post_image[0];?>" /></a>
                    <h4><?php echo get_the_date(); ?></h4>
                    <h3><?php the_title(); ?></h3>
                    <h5>
                        <?php $content= get_the_content(); 
                              echo $contentTrimmed = substr($content, 0, 100).'...';
                        ?>
                    </h5>
                    <ul>
                        <li>
                            <a href="#">Posted by
                                <span><?php echo get_the_author(); ?></span> |</a>
                        </li>
                        <li>
                            <a href="#">Comments
                                <span><?php echo get_comments_number(); ?></span> |</a>
                        </li>
                        <li>
                            <a href="#">Likes
                                <span><?php if (function_exists('wp_ulike_get_post_likes')){

                                            $count= wp_ulike_get_post_likes(get_the_ID());
                                            if($count > 0)
                                            {
                                              echo $count;
                                            }
                                            else
                                            {
                                               echo '0';
                                            }
                                        }
                                        ?>
                                </span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
            <?php 
                  $counter++;
                  if($counter%3==0) 
                  echo '</div><div class="row">';
                  endwhile; 
            ?>
        </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

Updating a DIV in JQuery with a new URL submitted through a form

I am working on a form that includes a text box within a div tag. My goal is to dynamically change the contents of this div based on the user input in the textbox using a PHP GET request. For example, if the user types "hell" into the textbox, I want the ...

"Transforming a div's data-src to an image_tag in Django - A Step-by-

I am struggling to display images in my project using static tags. I have tried various methods but none seem to work with the div tag. After unsuccessful attempts, I decided to seek help online but couldn't find a solution. Any assistance would be g ...

Having trouble bringing in css files

I'm having trouble loading a CSS file when trying to import it into another CSS file. I've tried various ways of defining the path but nothing seems to work. Any insights on what might be causing this issue? https://i.sstatic.net/IwaY1.png ...

Issue with child rows not functioning properly in DataTables when utilizing Datetime-moment

I've successfully integrated this data into live.datatables.net and almost have it running smoothly. However, I am encountering an issue with displaying the last detail as a child element. The final part of the row should be shown with the label "Mes ...

What causes delays in transition for 'margin' and 'padding' in webkit browsers?

I attempted to use CSS transition effects on the margin and padding properties. The goal was to create an illusion of a larger background upon hovering. To achieve this, I increased the padding and decreased the margin correspondingly on hover, ensuring t ...

In what way does Angular incorporate _page-theme.scss assets?

The Angular Material Documentation homepage includes a specific scss file: https://github.com/angular/material.angular.io/blob/master/src/app/pages/homepage/_homepage-theme.scss Although this scss file is not directly imported into the component's ...

Convert an AJAX JSON object into values for multiple text boxes

When making an ajax call, I receive the following JSON input: var json = { "id_u":"1", "nombre_usuario":"JESUS", "apellido_paterno_usuario":"DIAZ", } I have text inputs that correspond to each key in the JSON object: <input type="text" name="id ...

Tips for sending query string parameters to an AJAX request using data

Currently, I am making an ajax call to hit the API and I need to include a query parameter. How can I accomplish this with my ajax call? Below is the code snippet that I am using. Any assistance on this matter would be greatly appreciated. Thank you. ...

Understanding how to retrieve a particular list item in JQuery without having the index in advance

I have a lengthy list that is broken down into various subheadings. How can I retrieve the second to last element of the list before a specific subheading, provided it is not the final element? Is it possible to do this if I know the ID of the subheading? ...

Is the next function triggered only after the iframe has finished loading?

First and foremost, I understand the importance of running things asynchronously whenever possible. In my code, there exists a function known as wrap: This function essentially loads the current page within an iframe. This is necessary to ensure that Jav ...

Padding problem arises when you wrap an image with an anchor tag

I'm having an issue with a div containing an anchor-wrapped image, as there seems to be extra padding at the bottom of the div. How can I remove this? HTML: <div id="lineup"> <div class="line-up-click"> ...

Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays ...

Using jQuery dialog to load a form through AJAX and then submitting the form to the modal dialog

I have adapted pieces of code from various sources to create the following script. The links successfully load the edit form in a modal using ajax, but upon submitting the form, the entire page refreshes instead of just the modal. I am seeking a solution ...

Tips for choosing a parent element using SCSS

Here is an example of HTML: <ul id="navbar-main" class="navbar-nav mr-auto"> <li class="nav-item active"> <a href="https://travian.dev/materials" class="nav-link nav-materials"> <span class="invisible">Mater ...

What sets flex-start apart from baseline?

When using the align-* properties in flexbox, what sets flex-start apart from baseline? In the code snippet below, both align-self: flex-start and align-self: baseline produce the same result. Can you identify scenarios where align-self: flex-start and a ...

Feature allowing simultaneous playback of several audio files when activated within Aframe webVR

I have been experimenting with ways to make all the sound files in my A-frame VR project autoplay when the scene loads, but also include an on-window-click function for browsers that do not support autoplay or require user interaction. Although I believe ...

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

Blog Format Featuring Side-by-Side Columns

Is there a way to achieve horizontal columns that don't cut off articles and flow seamlessly into the next column? I want the columns to have varying heights, such as Post A at 60% height, followed by Post B at 40% height, then Post C at 30%, and fina ...

The ngOnChanges lifecycle hook is not being triggered

I've been working on a small project that involves two components: menu and bill. I'm trying to figure out how to make it so that when the quantity of any menu item is changed, the onChanges function in the bill component is called. I also need t ...

What is the best way to ensure that the correct Url.Action is passed to a JQuery method without encountering any issues with extra amp

I'm attempting to initiate an ajax call in this manner: $('#Grid').load('@Url.Action("_AgentStatesGrid", "AgentStates", new { projectId = Model.SelectedProject, siteId = Model.SelectedSite })', null, refreshComplete); Regrettabl ...