There are two things you need to set up first:
- 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).
- 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
<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)
{
cancelInterval(intervalID);
}
else
{
totalMoved += 10;
currElem.style.left = totalMoved + 'px';
}
}
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)
{
cancelInterval(intervalID);
}
else
{
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:
Post a Comment