English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm trying to make some image move every 5 seconds to the left when i press the left arrow key and I want it to stop moving when I press the other arrow keys.
I finished everything exept making the image stop on keydown.
I used setInterval to make the image move.
this is the code with setInterval in it.

var lefttime = setInterval ("moveleft()", 500)

I think im supposed to use document. onKeyDown(clearInterval (lefttime)) but it doesn't work.
could sumone explain how to do this?
and spaces between codes is because this site won't take long words so ignore those.

2006-06-08 13:13:12 · 1 answers · asked by Anonymous in Computers & Internet Programming & Design

1 answers

See my answer to your later post. Basically, hard code onkeydown to the body tag (dynamic assignment of events is best left for when it's actually necessary), and make sure lefttime is a global variable (declared oustide all functions so it's available to both the starting function and the stop function). Following is my post as an example:
So a simulation would be "as soon as user presses key, block moves forward, user presses key again to stop block." ?
In that case, how about abusing javascript's loose casting:

var animId = null;

function moveBlock() {do stuff}

function startMotion() {
animId = setInterval("moveBlock()", 42);
}

function stopMotion() {
clearInterval(animId);
animId = null;
}

function switchMotion() {
if(animId)
stopMotion();
else
startMotion();
}

Then, attached to your body tag, you have the event onkeydown="switchMotion()". Be careful with what happens when a user holds a key down. The casted Boolean value of a variable is true if it is anything other than the empty string "", the number 0, undefined, null, NaN, or the Boolean value false. See
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:if...else#Description .

2006-06-08 17:03:30 · answer #1 · answered by Ron 6 · 0 0

fedest.com, questions and answers