JSFiddle - React, Tailwind, and code Playground

by alexb

HTML

<span></span>
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>

CSS

div {
  display: inline-block;
  height: 100px;
  width: 100px;
  position: absolute;
  top: -30px;
  transition: all 0.5s ;
}

#a {
  background-color: red;
  left: 50px;
}

#b {
  background-color: blue;
  left: 200px;
}

#c {
  background-color: green;
  left: 350px;
}

span {
  display: inline-block;
  background-color: gold;
  border-radius: 50%;
  height: 25px;
  width: 25px;
  top: 137.5px;
  position: absolute;
}

JavaScript

const ball = document.querySelector('span');
const items = document.querySelectorAll('div');

function left(el) {
	const style = getComputedStyle(el);
  return parseFloat(style.left);
}

function swap(x, y) {
	const tmp = left(items[x]);
  items[x].style.left = left(items[y]) + 'px';
  items[y].style.left = tmp + 'px';
}

function rand(max) {
	return Math.trunc(Math.random() * (max + 1));
}

function shuffleTwo(n) {
	if (n > 0) {
  	const a = rand(2);
    let b = rand(2);
    while (a === b) {
    	b = rand(2);
    }
    setTimeout(() => {
			swap(a, b);
      shuffleTwo(n - 1);
    }, 500);
  }
}

function init() {
	ball.style.left = (87.5 + rand(2)*150) + "px";
  for (let x of items) {
  	x.style.top = "100px";
  }
  setTimeout(() => {
  	ball.style.visibility = 'hidden';
    shuffleTwo(10);
  }, 500);
}

init();