Reputation: 23
I'm doing a web app and I'm having issues with being able to type in text boxes without activating JavaScript events tied to key presses. I tried my best to figure out a way to disable all of these events while focused to the text box but to no avail. Is there any way to "focus" on text boxes to stop other events from running? Thanks.
Upvotes: 2
Views: 40
Reputation: 10604
Try the below code. On focus
removed all events listeners and on onblur
add all events listeners.
let input = document.getElementById('input');
//Attach all the events
input.addEventListener('focus', removeAllEventListner);
input.addEventListener('keypress', myFunction);
input.addEventListener('blur', addEvents);
//On focus remove all the events
function removeAllEventListner() {
input.removeEventListener('keypress', myFunction);
console.log('Event removed');
}
//Onblur add all event
function addEvents() {
input.addEventListener( 'onkeypress', myFunction);
console.log('Event attached');
}
function myFunction() {
console.log('Keypress event');
}
<input type="text" id="input" value="" >
Hope this will solve the issue.
Upvotes: 1