peterbetis
peterbetis

Reputation: 13

How to simulate a key press by pressing a different key

I want to hide the "suggested" options list that appears underneath the search input when you start typing something on the Wordpress search plugin, what I need specifically is to fire the "Escape" key event when I press down the "Delete" key, I tried the following jquery function but it doesn't work as I expected.

$('form.search-form').keydown(function (e) {

// keycode for Delete key
if (e.keyCode == 46) {
      var a = $.Event("keydown");
      // keycode for Esc key
      a.which = 27;
      a.keyCode = 27;
      $(document).trigger(a); 
}});

Any help? Thanks in advance

Upvotes: 1

Views: 3104

Answers (1)

m59
m59

Reputation: 43745

Updated (original question was unclear)

Live demo here (click).

When the delete key is pressed, change the keyCode to the esc key, then use trigger to simulate a press of esc.

$('input').keydown(function (e) {
  // keycode for delete
  if (e.keyCode == 46) {
    console.log('delete key pressed.');
    e.keyCode = 27;
    $(this.target).trigger(e);
  }
});

$('input').keydown(function (e) {
  // keycode for esc
  if (e.keyCode == 27) {
    console.log('esc key pressed.');
  }
});

Old answer (leaving this here because it is similar.)

Your question is an X/Y problem. You don't need to fire another keydown, event, you just need to repeat the same functionality, so extract the esc event's code into a function and reuse in the del key's event. Live demo here (click).

$('input').keydown(function (e) {
  // keycode for delete
  if (e.keyCode == 46) {
    myFunction(e);
  }
});

$('input').keydown(function (e) {
  // keycode for esc
  if (e.keyCode == 27) {
    myFunction(e);
  }
});

function myFunction() {
  alert('Look, Ma! Code reuse!'); 
}

Better yet, do this!

Live demo here (click).

$('input').keydown(function (e) {
  // keycodes for delete and esc
  if (e.keyCode == 46 || e.keyCode == 27) {
    myFunction(e);
  }
});

function myFunction() {
  alert('Look, Ma! Code optimization!'); 
}

Upvotes: 3

Related Questions