'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.



Solution 1:[1]

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

Solution 2:[2]

If you just want to detect the Ctrl key being pressed on its own, the following will work (although bear in mind that addEventListener is not supported in IE < 9, where you'd need to use attachEvent or onkeydown instead):

window.addEventListener("keydown", function(event) {
    // Bind to both command (for Mac) and control (for Win/Linux)
    if (event.keyCode == 17) {
        alert("Ctrl");
    }
}, false);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Miles
Solution 2 Tim Down