Tuesday, July 07, 2009

Moving Elements With Javascript

Moving HTML objects, or elements, is a very useful tool and can often replace annoying Flash. In this case, I'll be discussing sliding an element using JavaScript. I recently had to do this quite a bit while helping recreate my girlfriend's online portfolio and I decided to make a quick post about it.

There are two things you need to set up first:
  1. If necessary, give an ID to the element you wish to move (this is important if you're not using the element itself to initiate the moving process, which if you are, you can just use the "this" JavaScript keyword to pass a reference to the element).
  2. Set the element's CSS position property to absolute so it can be moved. Leaving it as default or relative will create some very frustrating times for you. Though you can set this in JavaScript when you call on the move function, I suggest setting up your page with the element already having this property since setting it at run time can screw up your page layout
Once they have been set up, moving an object really isn't that hard. Basically, you need to move the element a certain number of pixels every X number of milliseconds. Let's say you want an element to move 200 pixels to the right when clicked. You can use the following HTML:

<div style="width:200px;height:200px;background-color:blue;position:absolute;" onclick="javascript:Move(this);">

On click you can now fire this JavaScript function:

var currElem = null;
var intervalID = null;
var moveInterval = 10;
var totalMovement = 200;
var totalMoved = 0;

function Move(elem)
currElem = elem;
totalMoved = 0;
intervalID = setInterval('MoveElem()', 10);

function MoveElem()
if (totalMoved >= totalMovement)
totalMoved += 10;
currElem.style.left = totalMoved + 'px';

We set the currElem global variable because you can't pass variables to a method using an interval or timer. Then, once the is set, it's just a matter of incrementing the left amount (pushing the element to the right) until it's greater than or equal to the total amount you want it to move. You can then increase or decrease the top to get a diagonal and many other things. Varying the timeout time (in this case 10 milliseconds) and the interval distance will make the movement clunkier or smoother, depending on what you're looking for.

No comments: