Refresh the browser to update the content of specific columns

$(".home").append($(".home .coco").sort(() => Math.random() - 0.5));
.row{margin-bottom: 30px;}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript" ></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript" ></script>

<div class="home">
<div class="container">
<div class="row">
<div class="col-sm-3">A</div>
<div class="col-sm-3 coco">B</div>
<div class="col-sm-3">C</div>
<div class="col-sm-3">D</div>
</div>

<div class="row">
<div class="col-sm-3 coco">1</div>
<div class="col-sm-3">2</div>
<div class="col-sm-3 coco">3</div>
<div class="col-sm-3">4</div>
</div>

<div class="row>
<div class="col-sm-3">Red</div>
<div class="col-sm-3">Blue</div>
<div class="col-sm-3">Green</div>
<div class="col-sm-3 coco">Black</div>
</div>
</div>
</div>

Randomly rearrange the content of columns with the same class (coco) within their rows. The content is shuffled within the row and the column is removed from its current position.

Answer №1

If the elements in the .home list are only .coco items, then your method would be successful. However, it could cause issues if the list contains other items as well.

The suggested approach involves creating a duplicate of the .coco items, sorting them, and then iterating through the .home list to replace each .coco item with the corresponding sorted item.

$(function() {
    let sortedArrangement = $(".home .coco").clone().sort(function() {
        return Math.random() - 0.5;
    });
    
    $('.home .coco').each(function(index) {       
        $(this).replaceWith(sortedArrangement[index]);
    });
});

It is crucial to create a copy of the items to avoid potential issues where the newly replaced items might get replaced again.


Screenshot

https://i.sstatic.net/zabqR.png

Demo

https://jsfiddle.net/davidliang2008/7pb5n8ut/50/

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

"Exploring the world of asynchronous computations in jQuery Ajax: The next steps post-GET

When using ajax in jQuery with the request type, URL, and success functions, I often receive a JSON response. However, I face the challenge of needing to reformat the JSON arrays into a different structure, which can be computationally expensive. I am seek ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

Send an AJAX request to the specified `httpost` action method without any page refresh to load the

Today I have an interesting challenge that's been a brain teaser for me. While I may not be an expert in ASP.Net MVC4, I'm excited to tackle something new. The ultimate goal is to create a dynamic tree view for partial pages within a standard pag ...

Minimal Space Separating Footer Division and Body Element

While there are numerous discussions online about fixing footer alignment issues, I've encountered a unique problem that needs addressing. The issue at hand is a 29px gap between the bottom of the footer and the <body> tag on my webpage, which ...

IE10 is causing AJAX to return no results

I am currently using jQuery AJAX for my login page and it is working perfectly in all browsers except IE10. In IE10, I am getting an empty AJAX response. I'm not sure if this is a coding issue or a browser compatibility problem. Can someone kindly ass ...

Is SSG the best approach for deploying a Nuxt.js dashboard?

We have plans to create an internal dashboard utilizing Nuxt.js. Since this dashboard will be used internally, there is no requirement for a universal mode. Typically, most dashboards are designed as SPAs (Single Page Applications). However, SPAs still ne ...

JavaScript change the object into a string

I've been working on code to convert strings into dictionaries and arrays, and vice versa. While string to array and string to object conversions are successful, the reverse process is giving me trouble. I'm currently stuck and unsure of how to r ...

Ways for enabling the user to choose the layout option

I am looking to develop a customized reporting system where users can select the specific fields they want to include in the report as well as arrange the layout of these fields. The data for the reports is sourced from a CSV file with numerous columns. Us ...

It is impossible for tailwind to overflow while attempting to adjust the menu to the screen size

Here is the full code snippet: https://jsfiddle.net/3Lapnszc/1/ I am attempting to adjust the left navigation menu on the screen. <main class="flex flex-grow w-full h-screen"> <aside class="w-80 h-screen bg-gray shadow-md w-full hidden sm: ...

Turning a jQuery object and its contents into a string

Currently, I am selecting multiple jQuery objects to store in an array and then display them as HTML later on. I am attempting to transform the jQuery object into a text string so it can be displayed as HTML in the future. My current approach is as follo ...

A guide on implementing jQuery's .delay(1000) method for the same element

I have been attempting the code below without success. $("#mydiv").addClass('spin').delay(1000).$('#mydiv').removeClass('spin'); Do you have any recommendations on how to solve this issue? ...

utilizing ajax for pagination in a codeigniter application

I am currently working on setting up pagination in my controller code: <?php $nama = $this->session->userdata('nama'); $start_row = $this->uri->segment(3); $per_page = 5; if (trim($start_row) == '') { $start_row = 0; }; ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

Mongoose encountering an issue with undefined properties (specifically 'prototype') and cannot read them

I am currently using Mongoose 7.0.1 on Next JS 13.2.2 and React 18.2.0. After tirelessly searching for a solution to my problem, I am still struggling with connecting to a MongoDB. Every time I try to import mongoose into my project for the connection, an ...

Printing in Firefox is ineffective, but functions smoothly in alternative browsers

I'm currently working on customizing some content specifically for printing, so I've implemented a hook import { useState } from 'react' const usePrint = () => { const [isPrinting, setIsPrinting] = useState(false) const hand ...

Is there a way for me to design a button that includes an image?

I'm looking to create a button on my webpage using an image that will link to other pages. I want the flexibility to use both small and large text on this button. The specific image I want to use is: So far, I've attempted some coding but haven ...

What is the best way to pass a parameter with a slash in a GET request using jQuery's .ajax() function?

I'm currently faced with the task of generating a specific URL to make an API call using jQuery's .ajax() function: https://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=02144&date=2016-11-26&distance=25& ...

Encountered an unexpected identifier error while executing a Nuxt.js project

I am utilizing the following technologies: Node.js version 6.14.2 NPM version 6.0.1 Ubuntu 16.04 Whenever I attempt to execute a project, I encounter the following error message: npm run dev node_modules/nuxt/lib/core/module.js:14 async ready( ...

Can whitelist functionality be applied in the browser version of Babel?

While working on a project for my university, I wanted to utilize React. Since installation wasn't allowed, I had to resort to using the browser version of React. Everything was functioning well until I attempted to incorporate JSX into the browser. ...

How can you send Django context data to a JavaScript variable?

I need to send each value of the {{ i.nsn }} to the ajax script one by one. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} Instead of repeating the ajax script, I want it to function with a single click. <script> var nsn = " ...