0

I am trying to do the trigger keyDown event on click of a button, but this is not working.

$("#button").click(function() {
 var e = jQuery.Event("keydown");
 e.keyCode = 37; 
 $(this).trigger(e); 
 return false;
});

But the event is not triggering. Can anyone suggest please?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3750720
  • 163
  • 1
  • 13
  • https://stackoverflow.com/a/8692335/4298881, probably try e.keyCode = e.which = 37; as said in the comment. – Surely Oct 02 '17 at 14:40
  • [Yes, the event is triggering.](https://jsfiddle.net/ort0tjro/) But this area is [very well covered by previous questions](/search?q=%5Bjs%5D+simulate+keydown), what is it that's not answered about your issue in those questions' answers? – T.J. Crowder Oct 02 '17 at 14:40

1 Answers1

2

It looks to me like it's working.

Try the snippet below with the test function:

$(document).ready(function() {
  $("#button").click(function() {
    var e = jQuery.Event("keydown");
    e.keyCode = 37;
    $(this).trigger(e);
    console.log(e);
    return false;
  });
});

// test trigger
$(window).keydown(function(e) {
  key = e.keyCode ? e.keyCode : e.which;
  if (key === 37) {
    alert(`Left arrow triggered, (keyCode ${key})`);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Trigger key 37 (left arrow)</button>
Dan Kreiger
  • 5,358
  • 2
  • 23
  • 27