Jump to content

Moving Div


garyblackpool
 Share

Recommended Posts

Hi i have this code but cant change it to move div upto the top right. Could someone help thanks.

var x = 500; //Starting Location - leftvar y = 500; //Starting Location - topvar dest_x = 30;  //Ending Location - leftvar dest_y = 30;  //Ending Location - topvar interval = 10; //Move 10px every initializationfunction moveImage() {	//Keep on moving the image till the target is achieved	if(x>dest_x) x = x + interval; 	if(y>dest_y) y = y + interval;		//Move the image to the new location	document.getElementById("ufo").style.left  = y+'px';	document.getElementById("ufo").style.top = x+'px';	if ((x+interval > dest_x) && (y+interval > dest_y)) {		//Keep on calling this function every 100 microsecond 		//	till the target location is reached		window.setTimeout('moveImage()',100);	}}

Link to comment
Share on other sites

You have to detect if the ending point is before or after the beginning point:

if(x > dest_x) {  x -= interval;} else if(x < dest_x) {  x += interval}if(y > dest_y) {  y -= interval;} else if(y < dest_y) {  y += interval}// Just in case we're closer to the destination than the motion intervalif(Math.abs(dest_x - x) < interval) x = dest_x;if(Math.abs(dest_y - y) < interval) y = dest_y;if (x != dest_x && y != dest_y) {// Repeat the operation

Just for efficiency, use a function reference rather than an expression in setTimeout():

window.setTimeout(moveImage, 100);

Edited by Ingolme
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...