Check out this jQuery fiddle I'm using for my project: http://jsfiddle.net/BREvn/5/
Currently, I am creating a bird shooting game where the number of birds increases with each level. These birds are essentially represented by div elements, but I am facing an issue where they keep going out of the container and appearing in the bottom right position. What I want is for the divs to only touch the borders of the container.
Here is a snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="/js/jquery-2.0.2.min.js"></script>
<style>
div#container {height:50%;
width:50%;
border:2px solid white;
}
.a {
width: 120px;
height:120px;
position:relative;
}
</style>
<script type="text/javascript">
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function moveRandom(obj) {
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var pad = parseInt($('#container').css('padding-top').replace('px', ''));
var bHeight = obj.height();
var bWidth = obj.width();
maxY = cHeight ;
maxX = cWidth;
minY = cPos.top + pad;
minX = cPos.left + pad;
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX);
obj.animate({
top: newY,
left: newX
}, 1000, function () {
moveRandom(obj);
});
}
$('.a').each(function () {
moveRandom($(this));
});
</script>
</head>
<body>
<div id="container">
<img src="graphics-birds-917288.gif" class='a'/>
<img src="graphics-birds-917288.gif" class='a' />
<img src="graphics-birds-917288.gif" class='a' />
<img src="graphics-birds-917288.gif" class='a' />
<img src="graphics-birds-917288.gif" class='a' />
</div>
</body>
</html>