javascript check key is clicked

129 views Asked by At

I want to create code which invoked when I click CTRL key.

This is my code:

var ready = true;
$("document").ready(function(){
     readShift()
 });
 function readShift(){
    if (ready){
        $(window).keydown(function (e){
            if (e.ctrlKey){
                alert("clicked");
            }
        });
    }
    readShift();
}

After I click the CTRL key, the alert loop forever although after that I am not click CTRL.

What I need is the alert invoked just when I press CTRL.

4

There are 4 answers

0
Jørgen R On BEST ANSWER

The function calls itself recursively at the second to last line

function readShift(){
    ...
    readShift();
}

This means that even though the method finishes, it will be invoked over and over again.

Read this article on recusrion to understand what happenes.

0
Michael On

This is not useful:

if (ready){

The document is already ready because you are calling within a jQuery.ready.

It is going through an infinite loop because you are calling readShift(); recursively. This is the correct code:

$(document).ready(function(){
     readShift()
 });
 function readShift(){
        $(window).keydown(function (e){console.log("ciao");
            if (e.ctrlKey){
                alert("clicked");
            }
        });

}

EDIT: I also forgot to mention that $("document") is not getting any result, you should use $(document). jQuery makes a "query" inside the DOM. Unless there is a "document" tag in the DOM, $("document") is not finding anything

0
Roman On

try this code:

$("document").ready(function(){
    $(window).keydown(function (e) {
        if (e.ctrlKey){
            alert("clicked");
        }
    });
});
0
Der Vampyr On

When you call readShift() there is another readShift() inside of the function.

If you call this function, there are plenty of listeners on you keydown event. So when you click it, there are hundrets of alerts, because hundrets of listeners are triggered.

Remove readShift() from the function to get it work.