jQuery Move Div Left/right/up/down

We can smoothly move any element using jQuery .animate() method, the method basically changes value of css property of the element gradually to perform animation effect, the example shows how easily we can move DIV box to left, right, up and down with .animate() method.

Syntax

Almost all css properties can be animated using jQuery .animate() method, but the property names must be CamelCaseed (eg: margin-top becomes marginTop), here's syntax of jQuery animate method.(selector).animate({styles},{options})Now we know the syntax, we just need to apply this method to move our element :
JQUERY
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
<script type="text/javascript"> $(document).ready(function() { $('#moveleft').click(function() { $('#textbox').animate({ 'marginLeft' : "-=30px" //moves left }); }); $('#moveright').click(function() { $('#textbox').animate({ 'marginLeft' : "+=30px" //moves right }); }); $('#movedown').click(function() { $('#textbox').animate({ 'marginTop' : "+=30px" //moves down }); }); $('#moveup').click(function() { $('#textbox').animate({ 'marginTop' : "-=30px" //moves up }); }); }); </script> <div style="padding:20px;"> <button id="moveleft">Move Left</button>  <button id="moveright">Move right</button> <button id="movedown">Move Down</button> <button id="moveup">Move Up</button></div> <div id="textbox" style="position:absolute;padding:10px;background:#FFFFCC;width:300px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec tincidunt purus. Donec eleifend libero in orci mattis pulvinar. Ut et felis eu leo malesuada eleifend. Ut sit amet odio eu ipsum rutrum consequat. Aliquam congue ultricies sagittis.</div>

Demo

To move the box, click on buttons below, it should smoothly move up, down, left and right.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec tincidunt purus. Donec eleifend libero in orci mattis pulvinar. Ut et felis eu leo malesuada eleifend. Ut sit amet odio eu ipsum rutrum consequat. Aliquam congue ultricies sagittis.
  • Nice Demo, I want to move a text box in the same way but with dynamically fetched values.i.e. in place of that 30px value will be fetched dynamically from another text box and control should move according to that value.Can anyone help me out?
  • Hello.... nice one.... My case is.... I want to animate an image that fits exactly to the background but when i use marginLeft and marginRight the image is getting enlarged..... Same is not the case when I use marginTop..... Its going up fine...... Problem is with left and right... please help...... Thanks
New question is currently disabled!