Forum Moderators: open

Message Too Old, No Replies

Help moving a div more than once

         

Splejj

10:34 am on Oct 16, 2010 (gmt 0)

10+ Year Member



Hi, first time using javascript and stuck already! :(
I want to have a button that will move a div from one place to another, then a second that will move it back (I want to see it move)

I've got the following code that works once each way, then it just jumps from one side to the other instead of moving across slowly every time after that. Can anybody help me pleeease?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Image Mover</title>
<style>
DIV.movable { position:absolute; left:300px }
</style>

<script language="javascript">

var x = 300;
var y = 5;
var dest_x = 5;
var dest_y = 300;
var interval = 5;

function moveImage()
{
if(x>dest_x) x = x - interval;

document.getElementById("ufo").style.top = y+'px';
document.getElementById("ufo").style.left = x+'px';

if ((x > dest_x) && (y < dest_y))
{
window.setTimeout('moveImage()',100);
}
}

</script>

<script language="javascript">
var a = 5;
var b = 5;
var dest_a = 300;
var dest_b = 300;
var interva = 5;

function moveIm()
{
if(a<dest_a) a = a + interva;

document.getElementById("ufo").style.top = b+'px';
document.getElementById("ufo").style.left = a+'px';

if ((a < dest_a) && (b < dest_b))
{
window.setTimeout('moveIm()',100);
}
}
</script>
</head>
<body>
<div id="ufo" class="movable" style=" top: 5px; height: 104px">
<img src="butterfly.gif" />
</div>
<div style="margin-left:400px">
<button name="Abutton1" style="left:400px; width:100px; height:100px; " onclick="moveImage()">button</button>
<button name="Abutton2" style="left:500px; width:100px; height:100px; " onclick="moveIm()">button2</button>
</div>
</body>
</html>

daveVk

11:22 am on Oct 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You will need to reset x and y ( a and b ) so that the second time they start from same value.

eg

if ((x > dest_x) && (y < dest_y)) {
window.setTimeout('moveImage()',100);
} else {
x = 300;
y = 5;
}

Splejj

12:08 pm on Oct 16, 2010 (gmt 0)

10+ Year Member



Perfect thanks. I thought they might need resetting but wasn't sure how to go about ite