I have a piece of code where the user when he/she presses NumpadEnter
key, a certain function triggers:
document.addEventListener("keyup", function(event) {
if (event.code === "NumpadEnter") {
//some logic here
}
}
Now I want to trigger this keyup
function when a certain condition is met:
if(flag == true){
//trigger the keyup listener
}
How do I do that?
CodePudding user response:
Don't trigger the event. Instead place the logic in a separate function that both the event handler and the other code will call:
function performAction() {
// logic here
}
document.addEventListener("keyup", function(event) {
if (event.code === "NumpadEnter") {
performAction();
}
}
// Now I want to trigger this keyup function when a certain condition is met:
if (flag == true){
performAction();
}
CodePudding user response:
Put the keyup listener inside the flag checker. Then, pass a function to handle the event. Have that function as show here:
function handleEvent(event) {
if (event.code === "NumpadEnter") {
//some logic here
}
}
if(flag == true){
//trigger the keyup listener
document.addEventListener("keyup", handleEvent)
}