Not exiting first keypress event when parent function gets fired
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
});
});
Answer
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
});
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM