Ways to randomly rearrange div each time a new page is loaded

I wrote some code to shuffle my div elements when the page is reloaded, but I really want them to be shuffled every time a new visitor lands on the page. Since I am not an expert in jquery/javascript, I decided to reach out here for some guidance.

Here's the code snippet:

onload = function() {
  var parent = document.getElementById("shuffle");
  var frag = document.createDocumentFragment();
  while (parent.children.length) {
    frag.appendChild(parent.children[Math.floor(Math.random() * parent.children.length)]);
  }
  parent.appendChild(frag);
}

$(document).ready(function() {
  window.location.href = window.location.href;
});
#shuffle>div {
  float: left;
  line-height: 30px;
  width: 30px;
  text-align: center;
  background-color: steelblue;
  color: #fff;
  border-radius: 4px;
  margin: 3px;
}

#shuffle {
  max-width: 360px;
}
<div id="shuffle">
  <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>10</div>
  <div>11</div>
  <div>12</div>
  <div>13</div>
  <div>14</div>
  <div>15</div>
  <div>16</div>
  <div>17</div>
  <div>18</div>
  <div>19</div>
  <div>20</div>
</div>

Check out the jsfiddle here

EDIT - ISSUE RESOLVED! If anyone is interested in how this was fixed, you can view the updated jsfiddle here

Answer №1

Not sure what issue you're facing with your code, but you might want to try this alternative approach:

<div id="randomize">
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <div>D</div>
    <div>E</div>
    <div>F</div>
    <div>G</div>
    <div>H</div>
</div>

Using jQuery:

// Function to shuffle children within a container
function shuffleItems(container){
    let items = container.children();
    while (items.length)
        container.append(items.splice(Math.floor(Math.random() * items.length), 1)[0]);
}

// Call the shuffle function on the designated container
shuffleItems($("#randomize"));

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

Is the img tag showing an image from a folder, but not displaying the background-image?

Incorporating this code to showcase user uploads in a portfolio has been quite successful. However, I've run into an issue where one image (from a long list) appears blank on the page, but displays correctly on the following page when using the same p ...

Having an issue with loading checkboxes in a for loop using AJAX in jQuery Mobile, the .trigger() function is

I've been encountering a common problem online, and despite my best efforts, I can't seem to solve it. For those familiar with what I'm trying to do - I've successfully loaded static input content using .html(contentVariable), but thin ...

What is the best way for me to obtain cut documents?

I have a collection of documents similar to this: https://i.sstatic.net/s5IsG.png How can I retrieve specific fields, such as content.headline, content.description, content.tags, and id, from 11 documents using their corresponding _id values. To clarify ...

Tips and tricks for selecting a specific element on a webpage using jQuery

How can I modify my AJAX form submission so that only the content within a span tag with the id "message" is alerted, instead of the entire response page? $.ajax({ url: '/accounts/login/', data: $(this).serialize(), success: function(ou ...

Utilizing Javascript to compile a variety of JSON objects from a JSON request

I am looking to convert a json request input into a specific format required by the backend using javascript. Can anyone suggest the best way or steps to achieve this? Any assistance will be highly appreciated! Thank you. The request input is as follows: ...

Updates made in MobX store are not displaying in the web browser

Why are the data changes not reflecting in the view after the api call? Here is the code snippet that might help: store.js import axios from 'axios'; import {encrypt, decrypt} from '../utils/pgp.js' import {observable, action, compute ...

Exploring the different subcategories on osclassDiscovering the

Is there a way to display subcategories under a specific main category on osclass? For example, I want to show all subcategories linked with category id 2. How can this be achieved? Is there any code available for this task? ...

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

Styling errors in AngularJS validation code

I am facing an issue with the code below that generates 3 text boxes. When I click on one text box, all 3 of them get focused, despite having different name and label values. <div class="col-md-12" data-ng-repeat="dohPolicy in [1,2,3]"> <div ...

Is there a way to specify both a fixed width and a custom resizable length for a Spring <form:textarea /> element?

Despite extensive research, I have yet to find an answer to my specific problem. Within a model window, I have a textarea element: <div class="form-group"> <label for="groupDescription" class="col-sm-2 control-label"> Descripti ...

I am unable to append a new attribute to an object

I am currently working on a project using Node, Express, and Mongoose. In my controller, I'm trying to retrieve all orders for the logged-in client from the database. I want to display the status of each order and based on the state, add the available ...

Trigger a function with AngularJS when the page loads

I'm currently studying AngularJS. I have a set of article tags and want to display each article page without refreshing the page when a button is clicked. This website consists of only one page. The issue I am facing is that despite trying to call myF ...

React's sanitizer has refused these fonts

I've encountered font issues on my page while using react. Previously, everything was working fine but now I'm seeing the following error in the console. Attempted solutions like running npm audit --force (something along those lines). Addition ...

Creating a class dynamically in Angular 2 Typescript based on a property value

How can I dynamically assign classes in HTML based on a property in Angular 2 without using jQuery or Bootstrap? I am trying to open a dropdown list. Here is what I have: <li class="dropdown mega-menu mega-menu-wide" //stuck at adding class of op ...

Aligning the title vertically in Ionic on Android device

Currently, I am in the process of developing an application using the Ionic framework and cordova. After uploading my app for testing purposes, I encountered a small issue. The title in the top bar on Android appears to be misaligned vertically. Is there a ...

What are the best techniques for recreating the "Price Compare" responsive card layout?

Comparison of Plans on Desktop: https://i.sstatic.net/fzTeOJF6.png Mobile Plan Comparison: https://i.sstatic.net/2FBEmdM6.png Hello there, I'm seeking suggestions for designing this particular section of the layout. This section is visible both i ...

The client server is unreachable when running the npm run dev command

Having recently ventured into the world of npm and JavaScript, I find myself in a situation where I am attempting to utilize an existing npm project for local testing. Upon entering the command npm run dev, both the server and client scripts are activated ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

Display resize grip when hovering

Is there a way to make elements resizable using resize: both, but only show the corner handle when hovering over the element? https://i.sstatic.net/cGIYf.png I am looking for a solution to display that specific handle only on hover. ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...