JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div class="container">
</div>
</body>
CSS
.container {
height: 500px;
width: 900px;
background: #FF7A5A;
margin: 0 auto;
position: relative;
}
.box {
height: 50px;
width: 50px;
position: absolute;
top: 0px;
bottom: 0px;
background: #462066;
}
JavaScript
// Individual Box Class
function Box() {
this.element = document.createElement("div"); // div of the box;
this.posX; //X or Left position
this.posY; //Y or Top position
this.movePosX = 2 * (Math.floor(Math.random() * 2) == 1 ? 1 : -1); //move certain position in X direction, this will add minus sign in 50% of cases
this.movePosY = 2 * (Math.floor(Math.random() * 2) == 1 ? 1 : -1); //move certain position in Y direction, this will add minus sign in 50% of cases
var that = this;
this.addClass = function(className) {
that.element.className = className;
}
this.setInitialPos = function() {
this.posX = Math.floor((Math.random() * 850) + 1);
this.posY = Math.floor((Math.random() * 450) + 1);
that.element.style.left = that.posX + 'px';
that.element.style.top = that.posY + 'px';
}
this.appendTo = function(parentElement) {
parentElement.appendChild(that.element);
}
}
// MAIN CLASS OF THE APPLICATION
function BoxCollider() {
var boxes = []; //all the boxes
var container; //container where the boxes are kept
var totalBoxes = 30;
//instances
var box; //instance of box class
var boxAnimator;
var that = this;
this.init = function() {
container = document.getElementsByClassName('container')[0];
for (var i = 0; i < totalBoxes; i++) {
box = new Box();
box.addClass('box');
box.setInitialPos();
box.appendTo(container);
boxes.push(box);
}
that.startBoxCollider();
}
this.startBoxCollider = function() {
boxAnimator = new BoxAnimator(boxes);
// boxAnimator.animate(1);
}
}
var boxCollider = new BoxCollider();
boxCollider.init();