JSFiddle - React, Tailwind, and code Playground

by Adam Romine

HTML

<div class="shoo" id="fly0" onClick="swat()">
    <p>BUZZ</p>
</div>

CSS

body {
    padding: 0; 
	margin: 0;
	background-color: #000;
}

.shoo {
	width: 50px;
	height:50px;
	background-color:#555;
	color: white;
	text-align: center;
	position:fixed;
	cursor: pointer;
}

JavaScript

var i = 0;
var x = 0;

$(document).ready(function(){
	spawnFly();
});

function duplicate() {
  	var original = document.getElementById('fly'+i);
    var clone = original.cloneNode(true);
   	clone.id = "fly" + i++;
    clone.onclick = swat;
    original.parentNode.appendChild(clone);
}

function swat() {
	var id = $(this).attr('id');
	$('#'+id).remove();
	x--; // removes a fly from the swarm
}

function spawnFly() {
	if(x >= 15){
		alert("YOU LOST\n15 Flys have infested your screen!");
	}
	else if(x < 15) {	
		x++; // adds another fly to the counter	
		setTimeout(duplicate(), 2000); // spawns a new fly after a few secs
		animateDiv(); // animate the spawned fly
		spawnFly(); // called recursively until fly count is met
	}	
}

function makeNewPosition(){
    var h = $(window).innerHeight() - 50;
    var w = $(window).innerWidth() - 50;
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    return [nh,nw];    
}

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('.shoo').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    $('.shoo').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv();        
    });
};

function calcSpeed(prev, next) {
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    var greatest = x > y ? x : y;
    var speedModifier = 0.1;
    var speed = Math.ceil(greatest/speedModifier);
    return speed;
}