Keyup Event is not triggering on page load

1.6k Views Asked by At

I had implemented code to detect Key combination of "window logo key" + "up arrow" key event. I am showing alert message when user click inside text box and hold "Win + up arrow" . It was working fine manually. But i am trying to trigger same on page load, Its not working.

$(document).ready(function() {

  var e = jQuery.Event('keyup');
  e.metaKey = true;
  e.which = 38; //up arrow

  // Not working
  $("#test").trigger(e);

  // or

  // Not working
  $("#test").keyup();


  $("#test").keyup(function(e) {

    if (e.which == 38 && e.metaKey == true) {
      alert('win + Up arrow pressed');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="text" />

2

There are 2 best solutions below

2
On

Have you tried this way? You should have declared you event handler before calling a trigger.

 $( "#test" ).on( "keyup", function (e){ 
     if(e.which == 38  && e.metaKey == true) 
     {
        alert('win + Up arrow pressed');
     }
 });
 $( "#test" ).trigger( "keyup" );
4
On

This is because you have declared your event handler after the call to keyup.

So to make your code work, you have to write it ike this:

$(document).ready(function() {

    $("#test").keyup(function (e){ 
        if(e.which == 38  && e.metaKey == true) {
            alert('win + Up arrow pressed');
        }
    });

    $("#test").keyup();

});