Search code examples
javascriptjquerykeyctrl

javascript check key is clicked


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.


Solution

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