7

I have a custom CMS and would like to add a "shortcuts menu" triggered by the pressing of the Ctrl key twice within, say, 300 milliseconds. I use prototype, so my starting point obviously is:

Event.observe(document, 'keypress', function(event)
  { if(event.keyCode == Event.KEY_XYZ) { show_shortcuts});

My approach at the moment would be populating a global variable with the current time in milliseconds, and checking on each keypress whether a keypress has happened less than 300 milliseconds ago.

But maybe there is a more elegant solution?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • cant believe @Pekka 웃 have a question without upvote, was the first lol, and also found useful this question i was looking for double shift – ncubica Jun 22 '15 at 04:51

2 Answers2

9

This should work. Maybe add some further checking if not some other key like Alt or Shift are pressed at the same time. Hope it is self explanatory, if not just ask and I provide clarification.

var dblCtrlKey = 0;
Event.observe(document, 'keydown', function(event) {
  if (dblCtrlKey != 0 && event.ctrlKey) {
    alert("Ok double ctrl");
    dblCtrlKey = 0;
  } else {
    dblCtrlKey = setTimeout('dblCtrlKey = 0;', 300);
  }
});

https://jsfiddle.net/3tc26g7x/

jitter
  • 53,475
  • 11
  • 111
  • 124
  • It works, however it fires also when the Ctrl key remains pressed for 300 milliseconds. I will have to add a "keyup" checker but this will serve as a basis for it. Cheers! – Pekka Nov 10 '09 at 13:37
  • It doesn't fire for me when key remains pressed. Might be browser specific (I'm using Opera) – jitter Nov 10 '09 at 13:43
  • 1
    @Pekka just use `keyup` instead ;-) – yckart Dec 01 '12 at 17:26
  • @jitter i did try your solution however upon pressing ctrl even once the **dblCtrlKey** value prints as **139**. I wonder what am i missing. If you have a demo for the snipped, i'd really appreciate. – bijayshrestha Feb 19 '20 at 09:53
  • @bijayshrestha added a jsfiddle. The value of the `dblCtrlKey` variable is irrelevant – jitter May 06 '21 at 16:51
4

function doubleControlEvent() {
  if (event.key === 'Control') {
   timesCtrlClicked++
    if (timesCtrlClicked >= 2) {
      console.log('Double control')
      // Double Crtl is clicked add your code here
    }
    setTimeout(() => (timesCtrlClicked = 0), 200)
  }  
}

let timesCtrlClicked = 0;
document.addEventListener('keyup', doubleControlEvent, true)
Roland
  • 24,554
  • 4
  • 99
  • 97