Move Image randomly in Page with Jquery

by Rajdeep Chandra

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<i class="fa fa-car fa-3x"></i>

CSS

html,
body {
  height: 100%;
}

body {
  background: #09f;
  background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgeDE9IjAuNSIgeTE9IjEuMCIgeDI9IjAuNSIgeTI9IjAuMCI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwOTlmZiIvPjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iIzQ1ZDFmZiIvPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjZ3JhZCkiIC8+PC9zdmc+IA==');
  background-size: 100%;
  background-image: -webkit-gradient(linear, 50% 100%, 50% 0%, color-stop(0%, #0099ff), color-stop(100%, #45d1ff));
  background-image: -moz-linear-gradient(bottom, #0099ff, #45d1ff);
  background-image: -webkit-linear-gradient(bottom, #0099ff, #45d1ff);
  background-image: linear-gradient(to top, #0099ff, #45d1ff);
}

.fa {
  position: fixed;
  color: white
}

JavaScript

$(document).ready(function() {
  animateDiv();

});

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 animateDiv() {
  var newq = makeNewPosition();
  var oldq = $('.fa-car').offset();
  var speed = calcSpeed([oldq.top, oldq.left], newq);

  $('.fa-car').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.03;

  var speed = Math.ceil(greatest / speedModifier);

  return speed;

}