Jump to content

Moving Div


garyblackpool

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);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...