JSFiddle - React, Tailwind, and code Playground
by theoperatore
HTML
<div class="full-size blue">
<input type="button" id="change" value="Randomize"/>
<div id="circle" class="circle green"></div>
</div>
<div class="full-size green"></div>
<div class="full-size red"></div>
<div class="full-size grey"></div>
CSS
/* Reset */
*, *:before, *:after {
margin:0;
padding:0;
}
body,html {
width: 100%;
height: 100%;
}
.full-size {
width: 100%;
height: 100%;
}
.circle {
position: absolute;
height: 20px;
width: 20px;
border-radius: 50%;
top:30px;
left: 0;
transition: all 500ms ease-in-out;
}
.blue { background-color: rgba(82, 165, 255, 1); }
.green{ background-color: rgba(148, 255, 168, 1); }
.red { background-color: rgba(255, 148, 148, 1); }
.grey { background-color: rgba(201, 201, 201, 1); }
JavaScript
var circle = document.getElementById('circle'),
// the max height of this div is the window height
// minus the height of the circle.
max_y = window.innerHeight - 20,
// the max width of this div is the window width,
// minus the width of the circle
max_x = window.innerWidth - 20,
top = 0,
left = 0;
// call this function to change the position of the circle
function randomize() {
// get a random number between 0 and the max values.
top = Math.random() * max_y;
left = Math.random() * max_x;
// set the random location of the circle via top and left.
circle.style.top = top + "px";
circle.style.left = left + "px";
}
// when the window resizes, update the max values
window.addEventListener('resize', function() {
max_y = window.innerHeight - 20;
max_x = window.innerWidth - 20;
});
// click listener for button
document.getElementById('change').addEventListener('click', randomize);