...

View Full Version : Detecting double-press of a key



H3X
12-31-2010, 06:05 PM
I want to detect the double-press of the space key. However, I want a single press of a space key to have a different function. The double-tap of space should only count if the taps of space are no more than, say, a half second apart.

For example:
The user hits space once, and javascript begins performing one action. 1/3rd of a second later, they hit the space bar again, and since that is within our threshold of 1/2 of a second, the action that began because the user hit the spacebar once should be cancelled, or undone (which I can write later) and the action when the user hits the spacebar twice should begin.

Anyone have an idea how to do this? Thanks!

elitis
12-31-2010, 06:49 PM
You need to use onkeydown. If I'm understanding you correctly you want javascript to do something if the spacebar is pressed and then stop the action if the spacebar is pressed again within 1/3 of a second?

H3X
12-31-2010, 06:58 PM
You need to use onkeydown. If I'm understanding you correctly you want javascript to do something if the spacebar is pressed and then stop the action if the spacebar is pressed again within 1/3 of a second?
I know I need to use that, but I'm just not sure how I need to link everything together.

And, I want javascript to do something if the spacebar is pressed and then stop the action and start another one if the spacebar is pressed again within 1/2 of a second.

elitis
12-31-2010, 07:21 PM
I know I need to use that, but I'm just not sure how I need to link everything together.

And, I want javascript to do something if the spacebar is pressed and then stop the action and start another one if the spacebar is pressed again within 1/2 of a second.

Lets try getting the first part of that to work before moving on to the second part.
<head>
<script type="text/javascript">
function checkspace(event){if (window.event.keyCode == 32) alert('Stop that!');}
</script>
</head>
<body>
<BODY onKeydown="checkspace()"> Replace alert with whatever it is you want it to do.

amando96
12-31-2010, 07:31 PM
Then you could do a counter function that increments by 100 every 100ms, and do an if
var keypresses = 0;
var counter = 0;
startcouting();
if(event.keyCode == 32){
keypresses += 1;
}
if(keypresses == 2 && counter <= 500){
do something;
reset the counter;
}

That is coming from a not so good at JS guy, pardon me if there is a lot of failing.

amando96
12-31-2010, 07:36 PM
Edited

H3X
12-31-2010, 07:59 PM
Thanks guys, got it working on my own after tinkering for a while.

jmrker
01-01-2011, 03:39 PM
Thanks guys, got it working on my own after tinkering for a while.

Now that you have peaked our interest, :eek:
how about showing what you did to solve the problem :thumbsup:
in case others might want to use the technique! :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum