JSFiddle - React, Tailwind, and code Playground
HTML
<input value=" Stop " type="button" />
CSS
#box {
width:500px;
height:500px;
border:2px #000 solid;
position: relative; }
div.spec {
width:5px;
height:5px;
background-color:#00DDAA;
position:absolute; }
JavaScript
(function() {
var x, y, $elie, pos, nowX, nowY, i, $that;
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function ran(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function moveIt()
{
$("div.spec").each(function(i, v) {
x = ran(-5, 5);
y = ran(-5, 5);
$elie = $(v);
pos = $elie.offset();
nowX = pos.left;
nowY = pos.top;
$elie.css("left", nowX + x);
$elie.css("top", nowY + y);
});
}
$(function() {
$("body").append("<div/>").attr("id","box");
$elie = $("<div/>").attr("class","spec");
// Note that math random is inclussive for 0 and exclussive for Max
for (i = 0; i < 25; ++i)
{
$that = $elie.clone();
$that.css("top", ran(0, 495));
$that.css("left", ran(0, 495));
$("#box").append($that);
}
timer = setInterval(moveIt, 60);
$("input").toggle(function() {
clearInterval(timer);
this.value = " Start ";
}, function() {
timer = setInterval(moveIt, 60);
this.value = " Stop ";
});
});
}());