Answer the question
In order to leave comments, you need to log in
Shuffle sheet in jquery?
Hi hubr, there is such a design
<ul><br>
<li id="1">lorum</li><br>
<li id="2">ipsum</li><br>
<li id="3">beta</li><br>
</ul>
<ul><br>
<li id="1">beta</li><br>
<li id="2">ipsum</li><br>
<li id="3">lorum</li><br>
</ul>
Answer the question
In order to leave comments, you need to log in
Probably the best way would be to format it as a jquery function.
You can mix any collections.
Use $('ul').shuffle()
(function($){
$.fn.shuffle = function() {
return this.each(function(){
var items=$(this).children().map(function(){return $(this).contents()}).get();
items.sort(function(){ return 0.5 - Math.random() });
$(this).children().map(function(){$(this).empty().append(items.pop())});
return $(this);
});
}
})(jQuery);
function randSign() { return 0.5 - Math.random() }
// ...
$(function() {
var values = [],
items = $('ul li');
items.each(function(index) {
values.push( items.eq(index).text() )
})
values.sort(randSign)
items.each(function(index) {
items.eq(index).text( values[index] )
})
})
The easiest option, in my opinion.
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#button').click(function(){
var randomize = function(arr){
var length = arr.length - 1;
for (var i = 0; i <= length; i++){
var rnd1 = Math.round(Math.random()*length),
rnd2 = 0;
do{
rnd2 = Math.round(Math.random()*length);
} while (rnd1 == rnd2);
var tmp = arr[rnd1];
arr[rnd1] = arr[rnd2];
arr[rnd2] = tmp;
}
}
var items = [];
//заполняем массив содержимым списка
$('ul li').each(function(){
items.push($(this).html());
});
//перемешиваем
randomize(items);
//обновляем список
var length = items.length;
for (var i = 0; i < length; i++){
$($('ul li')[i]).html(items[i]); //возможно, это можно сделать как-то иначе
}
});
});
</script>
</head>
<body>
<ul>
<li id="1">lorum</li>
<li id="2">ipsum</li>
<li id="3">beta</li>
</ul>
<input type="button" id="button" value="Click me"/>
</body>
</html>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question