Reputation: 285
I need to move an absolute div relative to its parent using the Jquery animate function. How do I limit a CSS object literal left += -600px so that the left positioning stops when it reaches the end of the width? In other words I want to limit the left positioning of the element so that it doesn't keep moving off the page and out of view. Thanks for the help
Upvotes: 0
Views: 5047
Reputation: 18556
You could use the jQuery animate
's step
-function to check at each step whether the element has reached the edge of the page and should be stopped. HERE is a fiddle that demonstrates using the step function to stop the animation when a limit is reached.
...animate({left: '+=-600px'},
{
... ,
step: function(now, fx) {
if (fx.now <= 0) { // If the current animation value is less than zero
$(fx.elem).stop();
$(fx.elem).style('left', '0');
}
}
...
}
);
The step function gives you a nice way to control the animation step by step if necessary. Read here for more info.
Upvotes: 0
Reputation: 6960
To keep it lined up within the parent, you'll need to subtract the child width from the parent width, like so:
$(document).ready(function(){
var childWidth = $('#child').width();
var parWidth = $('#child').parents('#parent').width();
var offSet = parWidth - childWidth;
$('#child').animate({
left: '+=' + offSet
}, 1000);
});
Example HTML:
<div id="parent">
<div id="child">
I've been a bad child.
</div>
</div>
CSS:
* {
margin: 0;
padding: 0;
}
#parent {
width: 600px;
height: 200px;
background: green;
position: relative;
}
#child {
position: absolute;
background: red;
width: 100px;
height: 200px;
}
See this JSFiddle for a demonstration.
Upvotes: 0
Reputation: 7250
$(this).animate({'left': '-'+$(this).parent().width()}, [time in ms]);
Or if you meant the elements own width:
$(this).animate({'left': '-'+$(this).width()}, [time in ms]);
Upvotes: 2
Reputation: 7355
Well you didn't provide any code so my only guess is that you misunderstood how jQuery's animate function works. Actually jQuery's animate function does exactly what you want it to. It will increase the attributes of the element you want it to no more than you want it to. That is, it won't it keep moving it off the page and out of view unless you want it to. Here have a read how it works.
Upvotes: -1