Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing "control" keydown press event in Javascript

I'm trying to figure out when the user presses the control key in an HTML page using JavaScript.

In the following code "CTRL UP" will appear as expected, but "CTRL DOWN" will only appear if I also press another key, e.g. shift.

<html>
<head>
<script type="text/javascript">
window.addEventListener("keyup", function(event) {
  // Bind to both command (for Mac) and control (for Win/Linux)
  if (event.ctrlKey) {
    console.log("CTRL UP");
  }
}, false);

window.addEventListener("keydown", function(event) {
  // Bind to both command (for Mac) and control (for Win/Linux)
  if (event.ctrlKey) {
    console.log("CTRL DOWN");
  }
}, false);

</script>
</head>
<body>
Ctrl Demo
</body>
</html>

Is there any way to get the "CTRL DOWN" key event to work as expected, when ctrl is pressed and held down by itself?

NOTE: I'm trying to get this to work in a Google Chrome extension, so using Chrome specific APIs or tricks to make this work is completely fine. I'm using Google Chrome 15.0.874.83 beta on Ubuntu.

like image 224
oneself Avatar asked Nov 27 '22 02:11

oneself


1 Answers

Your code works for me, as does the following jQuery. (Chrome)

$(window).keydown(function(e){
    if (e.ctrlKey)
        console.log('Control Down');
});

Using alert is a little awkward because it blocks the process and you won't see any key state changes that occur while the dialog is up. I recommend using console.info/log/debug

like image 163
Miles Avatar answered Dec 05 '22 08:12

Miles