I'm attempting to create an animated effect where an image moves randomly within the boundaries of a div container. While I've come across solutions for animating within borders, none have specifically addressed keeping the image inside the div.
For example, I have a snippet that showcases a red square moving inside a yellow div, even as the page is scrolled.
How can I accomplish this?
$(document).ready(function() {
animateDiv();
});
function makeNewPosition($container) {
// Getting viewport dimensions (excluding the div's dimensions)
$container = ($container || $(window))
var h = $container.height() - 50;
var w = $container.width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var $target = $('.a');
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').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;
}
div#container {height:100px;width:100px;margin-left: 500px;background-color: yellow;}
div.a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>