How to randomly sort list items?

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 )

However, is there any better solution for that?



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();

            return Math.round(Math.random()) - 0.5;
        // }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'

    return this;

EDIT: Usage instructions below.

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


To randomize all children of each <ul>:


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.


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.

 // This code helps to shuffle the li ...
       $.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]

         // replace all elements with a plcaceholder
         for (var i = 0; i < elements.length; i++) {
           var placeholder = document.createTextNode('')
           findAndReplace(elements[i], 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)


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

       function listsort(){
       jQuery('.listify_widget_recent_listings ul.job_listings').each(function(index){
       // first time call to function ...
       // calling the function after the 15seconds.. 
         /// call your function here 5 seconds.
       }, 15000);                 

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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.