Randomize a List – Display HTML List Items Randomly with Javascript

To randomize a list in HTML with Javascript use the following codes

HTML CODE

<div class=”container”>
<h3>Shuffle List Randomly when page reload.</h3>
<ul id=”grid” class=”list-inline”>
<li>Runner: Alto’s Odyssey</li>
<li>Chess: Really Bad Chess</li>
<li>Puzzle: Mazes &amp; More</li>
<li>Platform: Once Upon a Tower</li>
<li>Arcade: Jungle Marble Blast</li>
<li>Brainy: Quizoid</li>
<li>Action: Tank Hero: Laser Wars</li>
<li>Puzzle: Sudoku</li>
<li>Shooter: Smash Hit</li>
<li>Racing: Traffic Rider</li>
<li>Action/Shooter: Major Mayhem</li>
<li>Fighting: Shadow Fight 2</li>
<li>Platformer: Shadow Blade Zero</li>
<li>Endless Runner: Crossy Road</li>
<li>Puzzle: Lazors</li>
<li>Racing: Asphalt Nitro</li>
<li>Strategy: Plants vs. Zombies 2</li>
<li>RPG: Pixel Dungeon</li>
<li>Sports: Flick Soccer</li>
<li>Board Game Sea Battle 2</li>
</ul>
<a href=”#” class=”btn btn-default”>Or click here to Shuffle</a>
</div>

CSS CODE

@import “compass/css3”;

.list-inline>li {
background-color: purple + 80;
margin-right: 15px;
margin-bottom: 15px;
padding: 10px;
color: white;
font-size: 26px;
}

JS CODE

// Global Variables
var grd = $(‘#grid’);
var imgs = grd.children();

// Page Refresh to run script below
imgs.sort(function(){
return (Math.round(Math.random()) – 0.5);
});
grd.remove(‘li’);
for(var i=0; i < imgs.length; i++)grd.append(imgs[i]);

//Click Functions to run the same script on top
$(‘a.btn-default’).click(function(){

imgs.sort(function(){
return (Math.round(Math.random()) – 0.5);
});
grd.remove(‘li’);
for(var i=0; i < imgs.length; i++)grd.append(imgs[i]);
});

 

Original Sourcecodepen.io/honminyue/pen/wBgzeK?css-preprocessor=sass