Looking at this question I was able to move my 2 divs around the screen randomly. Look at the CSS of the two divs containing the pictures:
div.a {
z-index: -101;
width: 95px;
height:95px;
position:fixed;
top: 100px;
left: 0px;
text-align: center;
}
div.b {
z-index: -102;
width: 100px;
height:100px;
position:fixed;
top: 300px;
right: 0px;
text-align: center;
}
div.a img, div.b img {
animation-name: giro;
animation-duration: 10000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
As you can see they are 2 divs with the classes a
and b
and inside they only contain a picture (using the tag img). Using the last piece of CSS the picutre rotates forever inside the div.
The div moves as well (together with the pictures), but he moves with the jQuery code below:
$(document).ready(function() {
animateDiv($('.a'));
animateDiv($('.b'));
});
function makeNewPosition($container) {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 100;
var w = $(window).width() - 100;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$target.animate({
top: newq[0],
left: newq[1]
}, speed, function() {
animateDiv($target);
});
};
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;
//speed of ----- --- moving around
var speedModifier = 0.03;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
The code above is the same as the one you can find in the question I linked. The only differences are the speedModifier
(from 1 to 0.03) and the two $(window).height()
and $(window).width()
because I need the divs to move around the entire screen.
PROBLEM
The fiddle in the question I linked works fine and the divs are moving forever at random positions. In my case (using my code) the divs are moving randomly in the entire screen for a bit but they they stuck in a point of the screen and they don't move anymore.
Is it because I set a too small speedModifier?