How to randomly sort list items?
Asked Answered
F

2

9

I currently have this code that randomly sorts list items:

var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
   return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);

However, is there any better solution for that?

Foti answered 28/1, 2013 at 4:26 Comment(0)
S
39

Look at this question and answer thread. I like this solution via the user gruppler:

$.fn.randomize = function(selector){
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function(){
        $(this).children(selector).sort(function(){
            return Math.round(Math.random()) - 0.5;
        // }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'
        }).detach().appendTo(this);
    });

    return this;
};

EDIT: Usage instructions below.

To randomize all <li> elements within each '.member' <div>:

$('.member').randomize('li');

To randomize all children of each <ul>:

$('ul').randomize();

ANOTHER EDIT: akalata has let me know in the comments that detach() can be used instead of remove() with the main benefit being if any data or attached listeners are connected to an element and they are randomized, detach() will keep them in place. remove() would just toss the listeners out.

Stalinabad answered 28/1, 2013 at 4:29 Comment(2)
The issue you cite has been updated to use detach() instead of remove() -- just an FYI in case somebody else is wondering where their other attached behvaiors went!Enlist
You should never shuffle lists by sorting them with a random comparator. See bost.ocks.org/mike/shuffle/compare.html for a pretty visual explanationVassal
J
0

I also stuck to such questions I search on google and come across one code. I modify this code for my uses. I also include the shuffle the list after 15 seconds.

<script>
 // This code helps to shuffle the li ...
(function($){
       $.fn.shuffle = function() {
         var elements = this.get()
         var copy = [].concat(elements)
         var shuffled = []
         var placeholders = []
         // Shuffle the element array
         while (copy.length) {
           var rand = Math.floor(Math.random() * copy.length)
           var element = copy.splice(rand,1)[0]
           shuffled.push(element)
         }

         // replace all elements with a plcaceholder
         for (var i = 0; i < elements.length; i++) {
           var placeholder = document.createTextNode('')
           findAndReplace(elements[i], placeholder)
           placeholders.push(placeholder)
         }

         // replace the placeholders with the shuffled elements
         for (var i = 0; i < elements.length; i++) {
           findAndReplace(placeholders[i], shuffled[i])
         }

         return $(shuffled)
       }

       function findAndReplace(find, replace) {
         find.parentNode.replaceChild(replace, find)
       }

       })(jQuery);

       // I am displying the 6 elements currently rest elements are hide.

       function listsort(){
       jQuery('.listify_widget_recent_listings ul.job_listings').each(function(index){
         jQuery(this).find('li').shuffle();
         jQuery(this).find('li').each(function(index){
           jQuery(this).show();
           if(index>=6){
             jQuery(this).hide();
           }
         });
       });
       }
       // first time call to function ...
       listsort();
       // calling the function after the 15seconds.. 
       window.setInterval(function(){
         listsort();
         /// call your function here 5 seconds.
       }, 15000);                 
</script>

Hope this solution helps....Have a great working time ..

Jayme answered 28/8, 2015 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.