Not exiting first keypress event when parent function gets fired

- 1 answer

Ad

Problem

I have a .keypress() event inside of a .click() event. The first time the user clicks on the element, everything works fine, but subsequent clicks trigger the .keypress() event again without "closing" the first one. I've tried adding event.cancelBubble = true; and an empty return statement to break out of the function, but it hasn't worked because predictably, the rest of the code in that execution doesn't get executed but the event is still active and a key press could still trigger it. Is there a way to close the .keypress() event when foo gets clicked?

Code

$(foo).click(function(){
    //Do stuff
    $(foo).keypress(function(event) {
        //Do stuff
    });
});
Ad

Answer

Ad

do you mean keypress called more than once?
in your code, every time you click foo, a new anonymous function will be added to keypress event.

unbind the previous keypress event handler before binding new handler

$(foo).click(function(){    
    //Do stuff    
    $(foo).off('keypress').on('keypress', function(event) {    
        //Do stuff    
    });    
});    
Ad
source: stackoverflow.com
Ad