My goal is to create a div that smoothly appears and disappears while moving randomly, but I'm having trouble as it seems fixed in place. Below is a snippet of the code causing issues. Currently, the div only fades in and out. Any assistance would be greatly appreciated.
CSS
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}
JAVASCRIPT
var opacidad = [0.0, 1.0];
var visibilidad = ['hidden', 'visible'];
$(document).ready(function () {
animateDiv();
});
function makeNewPosition() {
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 = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
movement(newq, speed);
};
function movement(newq, speed) {
var newqHalf = Math.floor(parseFloat(newq) / 2);
$('.a').animate({
top: newqHalf[0],
left: newqHalf[1],
opacity: opacidad[0]
}, speed).css({
visibility: visibilidad[0]
})
var newqDouble = Math.floor(parseFloat(newq) * 2);
$('.a').animate({
top: newqDouble[0],
left: newqDouble[1],
opacity: opacidad[1]
}, speed)
.css({
visibility: visibilidad[1]
}, 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;
}