Shuffling HTML content into sets of three rows

We have been working on randomizing a series of listings, arranging them in rows of 3 items each. Our goal is to display the entire list in a random order while breaking the line after every 3 entries. Although we have successfully implemented the layout using HTML and CSS, integrating JavaScript has proven to be quite challenging.

HTML - Presenting 2 rows of 3 items. Each row currently enclosed within a parent container

$(document).ready(function(){
      $('ul').each(function(){
            // obtain current ul
            var $ul = $(this);
            // get array of list items in current ul
            var $liArr = $ul.children('li');
            // shuffle array of list items in current ul randomly
            $liArr.sort(function(a,b){
                  // Generate a random number between 0 and 10
                  var temp = parseInt( Math.random()*10 );
                  // Determine if the number is odd or even
                  var isOddOrEven = temp%2;
                  // Decide whether to add 1 or subtract 1 based on whether the number is greater than 5
                  var isPosOrNeg = temp>5 ? 1 : -1;
                  // Return -1, 0, or +1
                  return( isOddOrEven*isPosOrNeg );
            })
            // append shuffled list items back to ul
            .appendTo($ul);            
      });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row__full-width">
    <div class="third-width-block" style="background-image: url('someimage.jpg')">
        <span class="rectangle_top"></span>
        <div class="table">
        <h5 class="title">Item Title 1</h5>
            <div class="block_content">
                <p class="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                <a class="btn btn__primary more_info_btn" href="www.google.ca">Learn More</a>
            </div>
        </div>
    </div>
    <div class="third-width-block" style="background-image: url('someimage.jpg')">
        <span class="rectangle_top"></span>
        <div class="table">
        <h5 class="title">Item Title 2</h5>
            <div class="block_content">
                <p class="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
                <a class="btn btn__primary more_info_btn" href="www.google.ca">Learn More</a>
            </div>
        </div>
    </div>  
    <div class="third-width-block" style="background-image: url('someimage.jpg')">
        <span class="rectangle_top"></span>
        <div class="table">
        <h5 class="title">Item Title 1</h5>
            <div class="block_content">
                <p class="description">etc...</p>
            </div>
        </div>
    </div>
</div>
<div class="row__full-width">
    etc...
</div>

Your assistance on this matter would be greatly valued!

Edit:

We have made some progress by utilizing the script below, adjusting the HTML above so that each "third-width-block" div also includes a "propertyBlock" class. The next step involves breaking the row after every third entry, which can easily be accomplished by wrapping every set of three "propertyBlock" divs in a wrapper with a "row_full-width" class.

Is there a way to implement this?

var cards = $(".propertyBlock");
for(var i = 0; i < cards.length; i++){
    var target = Math.floor(Math.random() * cards.length -1) + 1;
    var target2 = Math.floor(Math.random() * cards.length -1) +1;
    cards.eq(target).before(cards.eq(target2));
}

Answer №1

After streamlining your HTML and updating the script, I have enhanced it to select all the div elements and arrange them within the .target div in a randomized order. It would be more efficient to implement a proper shuffle method like the Durstenfeld algorithm rather than relying on this "arbitrary sort" function.

$(".piece")
 .get()
 .sort(()=> ~~(Math.random()*3)-1)
 .forEach(d=>$(".target")
  .append(d))
.piece {display:inline-block; width:30% }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
    <div class="piece">one</div>
    <div class="piece">two</div>
    <div class="piece">three</div>
 </div>
 <div class="row">
    <div class="piece">four</div>
    <div class="piece">five</div>
    <div class="piece">six</div>
 </div>
<div class="row">
    <div class="piece">seven</div>
    <div class="piece">eight</div>
    <div class="piece">nine</div>
</div>

<div class="target"></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

In Vue/Javascript, once the user reaches the top of the page, automatically scroll down to reveal an extra navigation bar

My goal is to achieve something similar to what is being done on Snapzu.com: When you reach the top of the window, you can keep scrolling to display different categories. I am looking to implement this functionality using Vue or Javascript, but I haven&ap ...

The positioning of sub-menu items is incorrect

I would like the subitems in the menu to be positioned directly under the main menu items instead of being slightly offset to the right. CSS ul#menu { float:left; width:100%; margin:0; padding:0; list-style-type:none; background-c ...

Tips on retrieving a <list> from an MVC controller and passing it to the view with jQuery and AJAX

How can I retrieve a list from an MVC controller to a view using jQuery AJAX without getting the error message [object Object]? Here is my AJAX code: $.ajax({ type: 'POST', contentType: 'application/json; ch ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

Adjust the font height to match the height of the viewport

Is it possible to make certain letters within a tag stretch to the height of the entire browser window, similar to the example shown in this link? (Take note of the 04). Instead of using an SVG image like in the example, I would like to achieve this effec ...

Angular: Truncating text based on element width - A guide

I am working on displaying a String text and determining how many words to hide based on the screen width. Here is my current approach: app.filter('words', function () { return function (input, words) { if (isNaN(words)) re ...

Vue.js is unable to render the template using Object

During this demonstration at https://jsfiddle.net/ccforward/fa35a2cc/, I encountered an issue where the template could not render and the data in resultWrong remained empty with a value of {} At https://jsfiddle.net/ccforward/zoo6xzc ...

Why isn't my image moving when I hover over it using Jquery?

I am struggling to make my images animate on mouse hover, but for some reason, it's not working at all. $(document).ready(function(){ $(function() { $('img.caption').hover(function(){ $(this).find(&a ...

What alternative methods can be used to store information locally without relying on local storage?

My goal is to create a mobile app for users to access personalized information without the need for usernames and passwords. I have experience with MySQL and MongoDB, but I'm considering using indexedDB or saving data to a JSON file within the app. An ...

The Ajax database browser page refresh feature updates the content without actually refreshing the entire page

I am encountering an issue with my AJAX and PHP database integration. I believe many novice Ajax programmers are facing a similar problem. Despite shortening the code, it remains lengthy so please bear with me. There's a button on the homepage index.p ...

Toggle the display of the following element with a sliding animation

Can you help me create 5 <p> tags that can toggle the display of a corresponding <div> element beneath them? I know I could individually name each pair, but that would require a lot of jQuery code. Currently, my setup looks like this: <p c ...

Issue with starting Jquery and Sequence.js plugin, no apparent errors displayed

One thought I have is that the insertion of the JavaScript at the end of the page instead of in the head tag may be causing an issue, although it has not been a problem before. The HTML code below: <div id="sequence"> <ul> <li ...

JavaScript encounters an error when attempting to access the database

In my PHP page postArticle.php, I have two dropdown lists for categories and subcategories. The subcategories are generated based on the selected category. To generate the subcategories, I am using JavaScript to call another PHP file called data.php. The ...

Using multiple versions of JQuery on a single page may result in dysfunctional features

Is there a need to load custom JavaScript on a page after it has fully loaded? This can be achieved using a third-party tool that allows execution on live pages of the website post-loading. However, encountering an issue where the page contains numerous J ...

Is it possible for Monaco Editor to accommodate nested tokens?

I have configured a custom language in the monaco editor, with two root tokens: [/^\[?[e|E][r|R][r|R][o|O][r|R]\]?\s.*/, 'error'], [/\d{1,4}(-|\/|\.|:)\d{1,2}\1\d{1,4}/, 'time'], Using this ...

Is there a way to handle the ajax request only when necessary, instead of processing it every few seconds?

Currently, I am working on an AJAX chat system using PHP, MySQL, JavaScript, and AJAX. I have a piece of code that retrieves all chat messages within a div using AJAX, with the function running every 2 seconds. My issue lies in the fact that the div autom ...

Ways to verify if an array contains two identical object values?

I am in search of a way to determine whether my array contains duplicate object values or not. Let's say I have the following array of objects: const array = [ { id: "id1", quantity: 3, variation: "red", ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

Incrementing the image name by 1 each time a new image is added to the directory

Currently honing my PHP skills and in the learning process. Developed a simple script that enables users to upload images to a directory on the server. I aim to append a number at the end of each image name to prevent duplication. Here is my attempt at i ...