Simulate Flexbox Order via AJAX
by Brian Layman
HTML
<div class="header">
Every 2 seconds this refreshes and changes the order to simulate an ajax call
</div>
<div class="container">
<div class="item item-1 color1">1</div>
<div class="item item-2 color2">2</div>
<div class="item item-3 color3">3</div>
<div class="item item-4 color4">4</div>
<div class="item item-5 color5">5</div>
<div class="item item-6 color6">6</div>
<div class="item item-7 color7">7</div>
<div class="item item-8 color8">8</div>
<div class="item item-9 color9">9</div>
</div>
CSS
html {
background: #f6faff;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
max-height: 35rem;
}
.item {
font-size: 2rem;
line-height: 1;
text-align: center;
padding: 3rem;
background: #dfeffd;
border: 3px solid #457fdc;
color: #457fdc;
margin: 6px;
}
html {
background: #f6faff;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
max-height: 35rem;
}
.item {
font-size: 2rem;
line-height: 1;
text-align: center;
padding: 3rem;
background: #dfeffd;
border: 3px solid #457fdc;
color: #457fdc;
margin: 6px;
}
.color1 {
background: #dfeffd;
border: 3px solid #457fdc;
color: #457fdc;
}
.color2 {
background: mistyrose;
border: 3px solid tomato;
color: tomato;
}
.color3 {
background: #f1e9f7;
border: 3px solid #a579cc;
color: #a579cc;
}
.color4 {
background: #f3edd6;
border: 3px solid #b59214;
color: #b59214;
}
.color5 {
background: #e2f0ef;
border: 3px solid #51aaa3;
color: #51aaa3;
}
.color6 {
background: #e2f0ef;
border: 3px solid 457fdc;
color: 457fdc;
}
.color7 {
background: 457fdc;
border: 3px solid #51aaa3;
color: #51aaa3;
}
.color8 {
background: tomato;
border: 3px solid #457fdc;
color: #457fdc;
}
.color9 {
background: #b59214;
border: 3px solid #f3edd6;
color: #f3edd6;
}
JavaScript
/* Randomize array in-place using Durstenfeld shuffle algorithm */
// SRC for shuffle: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
function applyCSS(item, index, arr) {
$("." + item).css("order",index);
}
function simulateAJAXUpdate(){
const boxes = ["item-1", "item-2", "item-3", "item-4", "item-5", "item-6", "item-7", "item-8", "item-9"];
// do whatever you like here
shuffleArray(boxes);
$(".container").hide(); // Add a visual clue of the change
boxes.forEach( applyCSS );
$(".container").fadeIn(1000); // Fade in works nicely
setTimeout(simulateAJAXUpdate, 3000);
}
$(document).ready(function(){
simulateAJAXUpdate();
});