JSFiddle - React, Tailwind, and code Playground

by Michaël van de Weerd

HTML

<div class="wrapper">
    <a id="1">news content 1</a>
    <a id="2">news content 2</a>
    <a id="3">news content 3</a>
    <a id="4">news content 4</a>
    <a id="5">news content 5</a>
</div>

<button onClick="shuffleElements()">Shuffle elements</button>
<button onClick="orderElements(true)">Order elements</button>

CSS

div.wrapper {
    width: 250px;
    height: 350px;
    background-color: red;
}

div.wrapper > a {
    height: 50px;
    width: 150px;
    border: 1px solid green;
    display: block; /* important */
    position: absolute;
}

JavaScript

// define the spreed of the animation in ms
$animationSpeed = 500;

// define the height of the content links in px
$contentHeight = 50;

// define a name by which the elements that should be moved can be indentified
$element = "div.wrapper > a";

// when the page is ready the elements should be given their initial position
$(document).ready(function() {
    orderElements(false);
});

/* order the elements as they appear in the HTML source */
function orderElements($animate) {
    // make everything extra complicated by having an option to make a smooth animation or not
    $animate = $animate === "undefined" ? false : $animate;
    
    // get the amount of elements to animate
    $amount = $($element).size();
    
    // give all elements their top margin
    for($i = 0; $i < $amount; $i++) {        
        // define the id of the currently selected element
        $id = $i + 1;
        
        // check if a smooth animation should be used and give the element it's initial top margin
        if($animate) {
            $($element + "#" + $id).animate({marginTop: $i * $contentHeight + "px"}, $animationSpeed);
        } else {
            $($element + "#" + $id).css("margin-top", $i * $contentHeight);
        }
    }
}

/* move the elements to a random order */
function shuffleElements() {
    // define the amount of elements
    $amount = $($element).size();
    
    // define the lowest possible top margin
    $topMargin = 0;
    
    // define an array to hold the id's of elements that are done
    var done = [0];
    
    // assign a top-margin to every element in a random order
    for($i = $amount; $i > 0; $i--) {
        // initiate a variable to hold the id of the element
        $id = 0;
        
        // keep regenerating a random number until it's not equal to a number in the array
        while(jQuery.inArray($id, done) != -1) {
            $id = Math.floor((Math.random() * $amount) + 1);
        }
        
        // push the new id to the array...