By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,940 Members | 1,522 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,940 IT Pros & Developers. It's quick & easy.

On second keypress (within a specified time frame)

P: 7
Hi

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.

Expand|Select|Wrap|Line Numbers
  1. var escapeCount = 0;
  2.  
  3. function reset() {
  4.     escapeCount = 0;
  5.     setTimeout('reset();', 1000);
  6. }
  7.  
  8. window.onload = function() {
  9.   reset();
  10. };
  11.  
  12. document.onkeyup = function(e) {
  13.   if (!e) var e = window.event;
  14.   var code = e.keyCode ? e.keyCode : e.which;
  15.   if (code == 27) escapeCount +=1;
  16.   if (escapeCount == 2) {
  17.     // stuff on second escape
  18.   }
  19. };
  20.  
  21.  
Is there a better way to do this? Thanks
Jan 22 '10 #1
Share this Question
Share on Google+
1 Reply


RamananKalirajan
100+
P: 607
Hi Akadeco,
This is one way I have tried for your requirement.

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <HTML>
  3. <HEAD>
  4. <TITLE> New Document </TITLE>
  5. <META NAME="Generator" CONTENT="EditPlus">
  6. <META NAME="Author" CONTENT="Ramanan Kalirajan">
  7. <META NAME="Keywords" CONTENT="Demo">
  8. <META NAME="Description" CONTENT="Demo">
  9. <script type="text/javascript">
  10. var lastChar = null;
  11. var lastTime = null;
  12.  
  13. function checkReplicate(e)
  14. {
  15.      if (!e) var e = window.event;
  16.      var code = e.keyCode ? e.keyCode : e.which;
  17.   if(lastChar==null)
  18.   {
  19.      lastTime = new Date();
  20.      lastChar = code;
  21.   }
  22.   else
  23.   {
  24.      var diffTime = (new Date()) - lastTime;
  25.      if(lastChar==code)
  26.      {
  27.         if(diffTime<1000)
  28.           alert("You have entered the same char twice");
  29.           return false;
  30.      }
  31.      else
  32.      {
  33.         lastTime = new Date();
  34.         lastChar = code;
  35.      }
  36.   }
  37.   return true;
  38. }
  39. </script>
  40. </HEAD>
  41. <BODY>
  42. <input type="text" onkeydown="return checkReplicate(event)">
  43. </BODY>
  44. </HTML>
  45.  
Thanks and Regards
Ramanan Kalirajan
Jan 22 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.