Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I randomize the order of two sets of elements in jquery/javascript, so that they remain in sync with each order?
    text
    copied!<p>Consider the following mark up:</p> <pre><code>&lt;div id="elements1"&gt; &lt;div&gt;Item 1&lt;/div&gt; &lt;div&gt;Item 2&lt;/div&gt; &lt;div&gt;Item 3&lt;/div&gt; &lt;div&gt;Item 4&lt;/div&gt; &lt;div&gt;Item 5&lt;/div&gt; &lt;/div&gt; &lt;br/&gt; &lt;ul id="elements2"&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;li&gt;Item 3&lt;/li&gt; &lt;li&gt;Item 4&lt;/li&gt; &lt;li&gt;Item 5&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I want to generate a random order that both of these lists would use. So a desired output could look like:</p> <pre><code>&lt;div id="elements1"&gt; &lt;div&gt;Item 2&lt;/div&gt; &lt;div&gt;Item 5&lt;/div&gt; &lt;div&gt;Item 3&lt;/div&gt; &lt;div&gt;Item 1&lt;/div&gt; &lt;div&gt;Item 4&lt;/div&gt; &lt;/div&gt; &lt;br/&gt; &lt;ul id="elements2"&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;li&gt;Item 5&lt;/li&gt; &lt;li&gt;Item 3&lt;/li&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 4&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><code>#elements1</code> will always have the same number of children in it as <code>#elements2</code> and visa versa.</p> <p>My pseudo code looks like like:</p> <pre><code>// see how many child elements in #elements1 // create order array based on # of child elements in i.e. [1,2,3,4,5] // randomize array // use order array to reorder both #elements1 and #elements2 // .appendTo() respective parents </code></pre> <p>Does my strategy seem like it would be efficient for the task at hand? (I will produce working code in a minute.) If not, what would be a better way to go about this? Thanks for your help!</p> <p>Edit: Here is a <a href="http://jsfiddle.net/fmpeyton/H4Crr/" rel="nofollow">fiddle</a> to mess around with.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload