admin管理员组文章数量:1404924
I have multiple 'li' elements:
$(".my_lis")
with on the page I want to shuffle them around with JavaScript (I'm using JQuery). How to do that?
I have multiple 'li' elements:
$(".my_lis")
with on the page I want to shuffle them around with JavaScript (I'm using JQuery). How to do that?
Share Improve this question asked Jan 25, 2012 at 21:10 TamTam 12k19 gold badges72 silver badges120 bronze badges 1- 2 When you say shuffle do you mean randomly mix their order? – ryanve Commented Jan 25, 2012 at 21:16
5 Answers
Reset to default 4It's not too hard actually. The general idea is:
- Grab all the dom nodes
- Shuffle them
- Empty the
<ul>
and insert the shuffled nodes
--
var items = $('.my_list li').get();
//edit (per ments): avoid confusion
items = shuffle(items);
$('.my_list').empty().append(items);
Where shuffle() can be anything that shuffles the array, I prefer underscore.js but here is a vanilla JavaScript way of doing a shuffle on an Array:
Just an example on shuffling ANY array
function shuffle(items) {
for(var index = 0, ln = items.length; index < ln; index++) {
var item = items[index],
swapIndex = ~~(Math.random() * ln),
swapItem = items[swapIndex];
//Swap places
items.splice(swapIndex, 1, item);
items.splice(index, 1, swapItem);
}
return items;
}
A reliable option is to insert a temporary dummy element after each element in the jQuery collection, then shuffle the current collection, and replace the elements in the dummy collection with elements from the shuffled list.
When appending a DOM element to another place, the element is automatically removed from the previous place.
Working demo: http://jsfiddle/ryEHm/2/
Code:
var $collection = $(".my_list li");
var shuffled = [];
$collection.each(function() {
shuffled.push(this); //Push DOM element
}).after('<span class="dummy"/>');
$('span.dummy').each(function(index) {
$(this).replaceWith(shuffled.splice(Math.random()*shuffled.length),1);
});
Maybe this plugin from James Padolsey helps you: http://css-tricks./snippets/jquery/shuffle-dom-elements/
Simply use it like this:
$('.my_lis').shuffle();
Here's a demo: http://jsfiddle/y4kyw/ – Press run to shuffle the list again
You can check out the jQuery Sortable plugin which has great examples and code walkthroughs/samples here:
http://jqueryui./demos/sortable/
jsfiddle demo
using
jQuery plugin to randomly reorder child elements with callback — Gist
to use: $(".my_lis").reorder();
本文标签: jqueryHow to swap element on screen with JavaScriptStack Overflow
版权声明:本文标题:jquery - How to swap element on screen with JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744877959a2630029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论