artrtrkli
artrtrkli

Reputation: 83

Randomly show paired elements

Is there a way to pair elements with the same class without wrapping

<div class="pair1">1</div>
<div class="pair1">2</div>

<div class="pair2">3</div>
<div class="pair2">4</div>

<div class="pair3">5</div>
<div class="pair3">6</div>

then randomly show paired element on page refresh/load so the output would be 1 2 or 3 4 or 5 6

FIDDLE here

Upvotes: 4

Views: 73

Answers (3)

Turnip
Turnip

Reputation: 36662

Working demo

var pairs = ['.pair1','.pair2','.pair3']; // Create an array of strings

var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random]; // choose a string at a random index in your array

$(output).show(); // use random string as selector

Or, if you have an arbitrary number of pairs you could construct your array on the fly with something like this:

Working demo

var pairs = [];

$('div').each(function() {
    var theClass = $(this).attr('class');
    pairs.push('.' + theClass);
});

var random = Math.floor(Math.random() * pairs.length);
var output = pairs[random];

$(output).show(); 

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can use that :

var pairs = $('.pair1, .pair2, .pair3');

var random = Math.floor(Math.random() * pairs.length / 2)+1;
var output = pairs.filter('.pair'+random)

output.show();

Since you have pairs, you'll need to divid the length by 2.

Then, when you have your random number, you get the pair number.

http://jsfiddle.net/tQ5ZP/2/

Upvotes: 4

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

var pairs = ['.pair1', '.pair2', '.pair3'];
var div = $("div[class^='pair']");

var random = Math.floor(Math.random() * pairs.length);
var output = div.filter(pairs[random]);

output.show();

DEMO

Upvotes: 1

Related Questions