I have an animated div placed inside a div, I only want this div to be able to move in the space of it’s parent. How would I go about doing that?
Simply: I want frog contained within frogger.
HTML
<div id="frogger"> <!-- Animate start -->
<button id="left">«</button> <button id="right">»</button>
<div id="frog">
</div>
</div> <!-- Animate end -->
CSS
#frogger
{
width: 500px;
height: 500px;
border: solid;
margin: 0 auto;
}
#frog
{
position:relative;
background-color:#abc;
left:50px;
width:90px;
height:90px;
margin:5px;
}
Javascript
$("#right").click(function(){
if ($(':animated').length) {
return false;
} else {
$("#frog").animate({"left": "+=50px"}, {queue: false}, "slow");
}
});
$("#left").click(function(){
if ($(':animated').length) {
return false;
} else {
$("#frog").animate({"left": "-=50px"}, {queue: false}, "slow");
}
});
One way is to test the current position and not move if it is too close to the edge:
Demo: http://jsfiddle.net/n3NgY/
Of course you can make this a bit more robust by determining the width of the frog and its container programmatically, but for the purpose of a quick demo I’ve just hardcoded the appropriate left and right boundary numbers.