Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 1.59 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. jQuery, random div order
  2. <div class="container">
  3.     <div class="yellow"></div>
  4.     <div class="red"></div>
  5.     <div class="green"></div>
  6.     <div class="blue"></div>
  7.     <div class="pink"></div>
  8.     <div class="orange"></div>
  9.     <div class="black"></div>
  10.     <div class="white"></div>
  11.     </div>​
  12. $("div.container div").each(function(){
  13.     var color = $(this).attr("class");
  14.     $(this).css({backgroundColor: color});
  15. });
  16.        
  17. $("div.container div").sort(function(){
  18.     return Math.random()*10 > 5 ? 1 : -1;
  19. }).each(function(){
  20.     var $t = $(this),
  21.         color = $t.attr("class");
  22.     $t.css({backgroundColor: color}).appendTo( $t.parent() );
  23. });
  24.        
  25. $.fn.sort = [].sort
  26.        
  27. var collection = $("div.container div").get();
  28. collection.sort(function() {
  29.     return Math.random()*10 > 5 ? 1 : -1;
  30. });
  31. $.each(collection,function(i,el) {
  32.     var color = this.className,
  33.         $el = $(el);
  34.     $el.css({backgroundColor: color}).appendTo( $el.parent() );
  35. });
  36.        
  37. var $container = $("div.container");
  38. $container.html(shuffle($container.children().get()));
  39.  
  40. function shuffle(o){
  41.     for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  42.     return o;
  43. };
  44.        
  45. var classes = [];
  46.  
  47. // Populate classes array
  48. // e.g., ["yellow", "red", "green", "blue", "pink", "orange", "black", "white"]
  49. $('div.container').children().each(function (i, v) {
  50.     classes.push(v.className);
  51. });
  52.  
  53. // Assign random color to each div
  54. $('div.container').children().each(function (i, v) {
  55.     var color = Math.floor(Math.random()*classes.length)
  56.     $(v).css({backgroundColor: classes.splice(color,1)});
  57. });