• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Relatively moving a div left or right with jQuery

Relatively moving a div left or right with jQuery

jQuery’s animate() function can do a lot of useful animation effects (see here for some more examples and documentation on the jQuery website). Something I found useful the other day is that it’s possible to move a div relatively left or right using the animate function, e.g. you can move it 50px to the right from its current position, instead of to an absolute position.

Working example

The easiest way to explain this is with a working example. If you are reading this in a feed reader then you’ll need to click through to read this post in a web browser otherwise it won’t work.

The text box "this is going to move" will move left or right by 50px each time the appropriate button is clicked.

This is going to move

The code

To move the div relative to where it currently is, set the ‘marginLeft’ property to a value += or -= the amount to move it by. The above examples effectively work like this:

$('#example').animate({
    'marginLeft' : "+=50px"
});

and

$('#example').animate({
    'marginLeft' : "-=50px"
});

Here’s the full code for the example above which actually calls a function to animate the div.

<script language="javascript">
function example_animate(px) {
	$('#example').animate({
		'marginLeft' : px
	});
}
</script>
<input type="button" value="Move Left" onclick="example_animate('-=50px')" />
<input type="button" value="Move Right" onclick="example_animate('+=50px')" />
<div id="example" style="border: 1px solid black; margin: 10px 0px; padding: 10px; background-color: rgb(238, 238, 238); width: 200px; text-align: center;">This is going to move</div>

Check Out These Related posts:

  1. CSS cursor property
  2. Show and hide an element with jQuery
  3. Using setTimeout() with Javascript
  4. Clear a form with Javascript

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap