Search code examples
jqueryeventskeydownonkeyupctrl

jquery: keydown, keyup, small snippet, why isn't this working?


Why isn't this working?

var holdingctrl = false;
$(document).keydown("q",function(e) {
 if(holdingctrl == true) 
 alert("Holding CTRL and pressing Q: Success.");
 e.preventDefault();
});

$(document).keyup("q",function(e) {
 holdingctrl == false 
});

This example below works just fine, but what am i doing wrong above?

$(document).keyup("q",function(e) {
 alert("ONLY pressing Q: Success.");
});

Solution

  • You needed a way to determine if control was currently being pressed (e.ctrlKey) - This should work for you:

      $(document).keyup(function(e) 
        { 
            if (e.ctrlKey && e.keyCode == 81) 
            {
                alert("CTRL+Q Pressed");
            }
        });
    

    Working Demo here