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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With