Search code examples
javascriptjquerykeypress

Start / Stop keypress event jquery


I have a problem. I want to stop keypress event when space is pressed, then I want to do something and finally I need to "restart" this function. It is possibile? How can I do this?

Thank you in advance

$(document).keypress(function(e) {
     if(e.keyCode == 32)
          // stop keypress function
          // do something
          // restart keypress function
}

Solution

  • I believe you have two choices.

    Disable the handler:

    $(document).on('keypress', function keypressHandler(e) {
        //disable handler
        $(document).off('keypress');
    
        //do stuff
    
        //enable keypress handler
        $(document).on('keypress', keypressHandler);    
    });
    

    Use a flag:

    var keyHandlerActive = true;
    $(document).on('keypress', function(e) {
        if (!keyHandlerActive) { return; }
        keyHandlerActive = false;
    
        //do stuff
    
        keyHandlerActive = true;    
    });