Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  103] [ 1]  / answers: 1 / hits: 63619  / 12 Years ago, mon, august 13, 2012, 12:00:00

I'm writing some unit test in my web apps and I want to automatically trigger an Enter key pressed event from my page after for example a download to text file button was clicked. How can i do this in jQuery or Javascript?


More From » jquery

 Answers
7

  1. Create a variable that tells us if the user has clicked your button.



    var clicked = false;

  2. Add an event listener to your button, so that when the user clicks on it, the clicked variable will become true.



    myButton.addEventListener('click', function(){
    clicked = true;
    });

  3. Add a keypress event listener:



    document.addEventListener('keypress', function(e) {
    // `e` is the event
    });

  4. Inside that event listener, check if the user clicked previously



    if(clicked) {
    // ...
    }

  5. If (s)he did, check the pressed key. Enter's key code is 13.



    var keynum = e.keyCode||e.which;
    if(keynum == 13) {
    // ...
    }

  6. If the pressed key was enter, use



    clicked = false;


    Otherwise, once the user clicked your button and pressed enter, it wouldn't be necessary to click the button again.


  7. After that run your code. For example, this will call function f after 2 seconds.



    setTimeout(f, 2000);



Live demo





var clicked = false;
document.querySelector('#btn').addEventListener('click', function(){
clicked = true;
snippet.log(You clicked the button. `clicked` is now `true`);
});
document.addEventListener('keypress', function(e) {
if(clicked) {
var keynum = e.keyCode || e.which;
if(keynum == 13) {
clicked = false;
snippet.log(`clicked` is now `false`. Waiting 2 seconds...);
setTimeout(f, 2000);
}
}
});
function f() {
snippet.log(Function `f` executed successfully!);
}

#btn {
border: 3px solid red;
cursor: pointer;
}

<div id=btn>Click me, and then press enter.</div>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><script src=http://tjcrowder.github.io/simple-snippets-console/snippet.js></script>




[#83684] Friday, August 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loric

Total Points: 110
Total Questions: 96
Total Answers: 91

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;