Sunday, May 19, 2024
137
rated 0 times [  142] [ 5]  / answers: 1 / hits: 27567  / 13 Years ago, tue, october 18, 2011, 12:00:00

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.


More From » google-chrome

 Answers
35

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


[#89566] Saturday, October 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaylea

Total Points: 459
Total Questions: 97
Total Answers: 106

Location: Denmark
Member since Wed, Aug 26, 2020
4 Years ago
;