-1

I have a code like this (static):

<a href="#">link 1</a>
<a href="#">link 2</a>
<a href="#">link 3</a>

I would like to know if it is possible to read these <a> tags and randomize their order with JQuery, so that it will (for instance) show:

<a href="#">link 1</a>
<a href="#">link 3</a>
<a href="#">link 2</a>
nico
  • 50,859
  • 17
  • 87
  • 112
Osny Netto
  • 562
  • 3
  • 9
  • 28
  • What is the source for the links? If using a DB then why not return them in random order. – Robert Jul 25 '12 at 17:57
  • possible duplicate of [Randomize a sequence of div elements with jQuery](http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery) – Mike Robinson Jul 25 '12 at 18:01
  • I'm nothing using DB (it's statis), the source don't matter in this case. – Osny Netto Jul 25 '12 at 18:05

4 Answers4

0

This will return the links in random order.

$("a").sort(function() {return 0.5 - Math.random()})

So I guess if you put the links in a container you can then repopulate it with the reordered array.

nico
  • 50,859
  • 17
  • 87
  • 112
0
var elems = $('a');
elems.sort(function() { return (Math.round(Math.random())-0.5); });  
for(var i=0; i < elems.length; i++) elems.parent().append(elems[i]);

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You can do it in your mysql query in the first place using ORDER BY RAND() or using JQUERY you can assign id to each a tags and append it randomly to its parent element using the this plugin: Random - jQuery plugin

Johndave Decano
  • 2,101
  • 2
  • 16
  • 16
  • I think his page is static, otherwise `ORDER BY RAND()` would be a good option when pulling links from a DB. – nico Jul 25 '12 at 18:07
0

All those sound good, but you could make a simple plugin in like so:

(function($) {
    $.fn.extend({
        randomize: function() {
            return $.randomize($(this).get());
        }
    });
    $.randomize = function(arr) {
        for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
        return $(arr);
    };
})(jQuery);

And then use it as such:

$("#someEleID").prepend($("a").randomize());

or:

$("#someEleID").prepend($.randomize($("a")));
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81