Please take a look at this:
http://jsfiddle.net/tmPfV/
If you click right the box moves right and if you click left the box moves left. However if you click right again, nothing...
How can I get it to move right and left as many times as I like instead of it working for one round and then not working again?
Also if you clock left first and then right it also messes up, how to solve that?
jquery:
$('.right').click(function(e) {
e.preventDefault();
$('#foo').animate({
'right' : '30px'
});
});
$('.left').click(function(e) {
e.preventDefault();
$('#foo').animate({
'left' : '30px'
});
});
html:
<a href="" class="left">left</a> | <a href="" class="right">right</a>
<br /><br />
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>
The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect. Only numeric values can be animated (like "margin:30px").
jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);
The animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality. Note: Not all CSS properties are animatable.
The second time it tries to animate, it already has 30px right positioning left over from the first animation.
As to why it jumps at the start of the left animation; the body has padding, so by default the sliding block is indented with padding. When we set the left
property to 0 at the beginning of the animation, it jumps outside the padding (to the absolute position of 0px left). Apply a body padding of 0px to fix it.
http://jsfiddle.net/MbJJ6/
$('.right').click(function(e) {
e.preventDefault();
$('#foo').css({ 'right': '0px', 'left': '' }).animate({
'right' : '30px'
});
});
$('.left').click(function(e) {
e.preventDefault();
$('#foo').css({ 'right': '', 'left': '0px' }).animate({
'left' : '30px'
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With