Relatively moving a div left or right with jQuery

Posted in Javascript -

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>


Related posts:


Comments