0

I'm here struggling to figure out how to implement and what methods to use Jquery for the following purpose.

Scenario:

The user places the mouse cursor over input and it must automatically simulate a keydown (KeyCode: 40) in that input. This event serves to automatically call up a list that is only triggered by this key. Whenever the user places the cursor on the input, he must automatically simulate a keydown. At the moment the user has to click arrowdown but I want this process to be automatic

$( "#input" ).click(function() {
    $("#input").trigger(jQuery.Event('ArrowDown', { keycode: 40 }));   
});

Thank you for your help. I'm out of ideas here :(

  • what kind of list, are you looking kind of select box feature ? – Learner Jun 04 '20 at 16:50
  • 1
    Does this answer your question? [Definitive way to trigger keypress events with jQuery](https://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery) – matthias_h Jun 04 '20 at 16:54

1 Answers1

0

function arrowDown(ev) {
  console.log(`Arrow down by ${ev.type}`);
}

$('input[name="foo"]').on({
  mouseenter: arrowDown,
  keydown(ev) { if (ev.key === "ArrowDown") arrowDown(ev); },
});
<input type="text" name="foo">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Or using the Event directly:

function arrowDown(ev) {
  if (ev.key === "ArrowDown") {
      console.log(`Arrow down by ${ev.type}`);
  }
}

$('input[name="foo"]').on({
  keydown: arrowDown,
  mouseenter(ev) {
    $(this).trigger( jQuery.Event({type: "keydown", key: "ArrowDown"}) )
  }
});
<input type="text" name="foo">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Thank you. Unfortunately, it didn't work. First, activate the function when I do mouseover. I wanted it to be when the user places the cursor on the input. Therefore click. Then I'm not simulating the keydown :(. The function I added results in a certain part. When I click it, it activates but for some reason I can't simulate the ArrowDown – PedroEstevesAntunes Jun 04 '20 at 17:24