Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger a keyup event function on meeting a certain condition in vanilla javascript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading