Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an UP or DOWN ARROW key event through javascript

Tags:

javascript

There is some event listener in Thunderbird which resolves the emails address from my LDAP server when i press the UP or DOWN ARROW key. so i want to trigger that the same event through Javascript without having to physically press the up or down arrow key. How can i do this?

like image 844
Rishab Gupta Avatar asked Feb 05 '15 15:02

Rishab Gupta


People also ask

How do you code arrow keys in JavaScript?

To detect the arrow key when it is pressed, use onkeydown in JavaScript. The button has key code. As you know the left arrow key has the code 37. The up arrow key has the code 38 and right has the 39 and down has 40.

What is keypress event in JavaScript?

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.

How do you press Enter in JavaScript?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.


1 Answers

I believe this is what you want (using JQuery)

var e = jQuery.Event("keyup");

// e.which is used to set the keycode
e.which = 38; // it is up
e.which = 40; // it is down
$("id_to_element").trigger(e);

If JQuery is not allowed to use, pure javascript solution is more verbose. See this answer

Note: There maybe a bug in Chrome which will hamper this. I would recommend JQuery for less headache.

like image 144
a_pradhan Avatar answered Oct 05 '22 12:10

a_pradhan