JSFiddle - React, Tailwind, and code Playground

by bestiole

HTML

<div class='a'></div>
<div class='b'></div>

CSS

div.a {
  width:50px;
  height:50px;
  background-color:red;
  position:fixed;
}
div.b {
  width:50px;
  height:50px;
  background-color:#00ff00;
  position:fixed;
}

JavaScript

var a;
var b;

$(document).ready(function(){
    a = $('.a');
    b = $('.b');
    animateDivA();
    animateDivB();
});

function makeNewPosition(){
  // Get viewport dimensions (remove the dimension of the div)
  var h = $(window).height() - 50;
  var w = $(window).width() - 50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh,nw];
}

function animateDivA(){
  var newA = makeNewPosition();
  var oldA = a.offset();
  var speed = calcSpeed([oldA.top, oldA.left], newA);
  
  a.animate({ top: newA[0], left: newA[1] }, speed, 'linear', function(){
    animateDivA();
  });
};

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.4;
  var speed = Math.ceil(greatest/speedModifier);
  return speed;
}

function animateDivB(){
  var target = a.position();
  var source = b.position();
  var slowness = 100;
  var top = (target.top+(source.top*slowness))/(slowness+1);
  var left = (target.left+(source.left*slowness))/(slowness+1)
  b.css({'top':top,'left':left});
	requestAnimationFrame(animateDivB);
}