Randomize the order of DIV elements inside another DIV

I am currently in the process of developing a new website, and we are looking to randomize a group of DIV elements within a document that have a specific class called 'shuffle':

(function($){

$.fn.shuffle = function() {

    var allElems = this.get(),
        getRandom = function(max) {
            return Math.floor(Math.random() * max);
        },
        shuffled = $.map(allElems, function(){
            var random = getRandom(allElems.length),
                randEl = $(allElems[random]).clone(true)[0];
            allElems.splice(random, 1);
            return randEl;
       });

    this.each(function(i){
        $(this).replaceWith($(shuffled[i]));
    });

    return $(shuffled);

};

})(jQuery);

The structure of my DIV elements is as follows:

<div class="row animate-in shuffle" data-anim-type="fade-in-up">
            <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
                <div class="team-wrapper">
                    <div class="team-inner" style="background-image: url('assets/img/team/1.jpg')">
                        <!-- <a href="#" target="_blank" > <i class="fa fa-twitter" ></i></a> -->
                    </div>
                    <div class="description">
                        <h3> Test User 1</h3>
                        <h5><strong> Tester - Inhaber </strong></h5>
                        <p>
                            fon: 1234567890<br>
                            <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe8a9b8d8abe8a9b8d8ad09a9b">[email protected]</a>">e-mail: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe8a9b8d8abe8a9b8d8ad09a9b">[email protected]</a></a><br>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
                <div class="team-wrapper">
                    <div class="team-inner" style="background-image: url('assets/img/team/2.jpg')">
                        <!-- <a href="#" target="_blank" > <i class="fa fa-twitter" ></i></a> -->
                    </div>
                    <div class="description">
                        <h3> Test User 2</h3>
                        <h5><strong> Tester </strong></h5>
                        <p>
                            fon: 0987654321<br>
                            <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9a8b9d9a8b9cdcae9a8b9d9ac08a8b">[email protected]</a>">e-mail: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="493d2c3a3d2c3b7b093d2c3a3d672d2c">[email protected]</a></a><br>
                        </p>
                    </div>
                </div>
            </div>
         </div>

Here's how I initiate the shuffling on page load:

$('div#shuffle div').shuffle();

Despite implementing the shuffle function, the elements remain in the same order as they appear in the document. Can anyone point out where I might be going wrong?

Appreciate any insights provided :)

Answer №1

Let's explore a solution to the problem at hand. Take inspiration from this example and adapt it to fit your specific needs.

Check out the code on FIDDLEJS

HTML Code:

<div id="container">
  <div class="shuffleMe"> DIV 1</div>
  <div class="shuffleMe"> DIV 2</div>
  <div class="shuffleMe"> DIV 3</div>
  <div class="shuffleMe"> DIV 4</div>
  <div class="shuffleMe"> DIV 5</div>
  <div class="shuffleMe"> DIV 6</div>
</div>
<button onclick="shuffle()">
  SHUFFLE
</button>

JavaScript Code:

function shuffle() {
  var container = document.getElementById("container");
  var elementsArray = Array.prototype.slice.call(container.getElementsByClassName('shuffleMe'));
    elementsArray.forEach(function(element){
    container.removeChild(element);
  })
  shuffleArray(elementsArray);
  elementsArray.forEach(function(element){
  container.appendChild(element);
})
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

Answer №2

If you want to randomize the order of elements in an array, one approach is to create an array with all the elements and then use a function to shuffle them. Here's an example of how you can achieve this:

function shuffleArray(array) {
    for (let i = array.length; i; i--) {
        let j = Math.floor(Math.random() * i);
        [array[i - 1], array[j]] = [array[j], array[i - 1]];
    }
}

After shuffling the array, you can re-render the parent container to display the elements in their new randomized order.

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

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

Overflowing dropdown menus on a dynamic navigation bar

After creating a navigation bar with dropdown links, I encountered an issue where hovering over the link to open the drop-down caused it to overflow to the right. Since the button is positioned at the right end of the navbar, it resulted in the scrollbar a ...

Having trouble with uploading a file through ajax

I'm currently working on uploading form data through ajax, but I've encountered an issue with uploading images/files. Form Code <form class="form-inline" id="form_add" enctype="multipart/form-data"> <input type="file" id="file-inpu ...

Can you please advise me on where I should send this request?

Whenever I click the button, my intention is to trigger a function that will transfer data to the template and open it up. Here's the code for the button click function: function openForm () { const amount = select.value; $ .ajax ({ ...

Leverage the router through the getServerSideProps method

My goal is to automatically redirect the user to the login page if their token has expired. I need to handle this in the getServerSideProps method where I make a request to the server for data. If the request is unauthorized, I want to use the useRouter ho ...

Full options in Bootstrap Selectpicker are not being displayed

I am currently facing an issue with a searchable list containing nearly 2700 items in a bootstrap selectpicker. When I scroll down the options, only around 50 or 60 are displayed, leaving the rest empty. You can view this problem in detail by checking out ...

Incorporate CSS styling within a PHP document

Many individuals are aware that HTML can be embedded within a PHP file. However, can CSS also be included in a PHP file and accessed using <link rel="stylesheet" type="text/css" href="mystyle.php" /> to make it act as a CSS file? While it is possib ...

jQuery show/hide function malfunctioning

Currently, I am attempting to create a basic show/hide interaction for a div using jQuery. The goal is to make the artists-home div vanish and be replaced by the .ken-gallery when the .artist-ken is clicked. Here is my current code, although it is not fun ...

Guide on crafting a query with typeorm query builder to extract specific data from the database

I'm a beginner with typeorm in nodejs/nestjs and I'm struggling to create a query to filter course data by instructor's firstname and lastname, course name, and subject. I've tried using 'where' and 'orWhere' but can ...

An error cannot be captured within the map function in Javascript

Imagine having a list of users like the following: var usersList = [ { firstName: 'Adam', lastName: 'Yousif', age: 23 }, { firstName: 'Mohamed', lastName: 'Ali' }, { firstName: &ap ...

Set up a function to run for the first time using window.setInterval after a two-second delay, and then continue to

I have a JavaScript function that I want to run in a specific way: (function($){ $(document).ready(function(){ $(function () { index = 0; window.setInterval(function () { if (index > 10){ index ...

Interfacing Node JS with Java Web Services via SOAP

I've been attempting to connect Java web services from a Node.js module, but I'm encountering an error in the wsdl library. Below is my wsdl file: <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130 ...

Ways to .focus() on input field while using Modals in Bootstrap

When I activate this Modal, I would like the mouse cursor to automatically focus on the textbox Therefore, my goal is to ensure that the textbox receives focus() upon modal opening. This involves both CSS and JS files <link rel=& ...

Serialization in .NET and the weekcalendar: events that are not defined

I've been attempting to integrate the jQuery weekcalendar within a .net environment. The issue I'm encountering is that after making an ajax call to a custom webmethod that returns JSON, the weekcalendar plugin reports that events.events is undef ...

The issue of border-radius and shadow box inconsistency

I'm trying to style a div with the following properties: .example { margin: 200px; width: 200px; height: 200px; border-radius: 20px; box-shadow: white 0px 0px 0pt 8pt, #033354 0px 0px 0pt 11pt; } <div class="example"> </div> ...

Using THREE.js in the pre-render function

I am encountering difficulties with updating the positions of my enemies before rendering them. Instead of creating a separate update() function, I attempted to use an onBeforeRender() function attached to each enemy object. However, nothing seems to be ...

Updating ng-model upon paste command in Safari browser encountering issues

When typing text character by character into a search textbox, everything works fine. However, when pasting data directly into the textbox, the ng-model does not get updated. This issue only occurs in the safari browser. Here is the HTML code: <div cl ...

"Effortlessly search and replace text with a click of a button using jQuery - A beginner

Is there a way to implement a search and replace function for text on button click using jQuery or JavaScript? For example, in Visual Studio, pressing ctrl + f opens a box that allows for text replacement. Is it possible to achieve the same functionality ...

Achieving victory through res.send

Currently, I am utilizing a combination of Node and Angular JS, in addition to express-4. Within my code, the issue arises when I attempt to transmit newSourceId using res.send. Despite successfully retrieving the newSourceId, it consistently triggers an ...

What is the best way to emphasize a label upon clicking a radio button?

I am trying to update the label of a radio button when it is clicked, but I have been unsuccessful so far. I came across this answer which seemed promising, but it did not work for me. Here is my code: HTML <div class="same-line"> <input typ ...