Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Escape key press event by jquery

I want to make my question clear. Please dont confuse it with determining the key press. I dont want the user to press any key. On the contrary, I want to run a script which fires the Escape key press event. Please help!

like image 349
Lakshay Avatar asked Apr 09 '12 07:04

Lakshay


People also ask

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

How do I know if my Esc is pressed?

To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard. keyup event: This event is fired when key is released from the keyboard.

What is escape keycode?

On computer keyboards, the Esc key Esc (named Escape key in the international standard series ISO/IEC 9995) is a key used to generate the escape character (which can be represented as ASCII code 27 in decimal, Unicode U+001B, or Ctrl + [ ).


2 Answers

You can use $.Event() to create an Event object containing a keydown event with the keyCode of 27 (which should be Esc) like:

var esc = $.Event("keydown", { keyCode: 27 });
$("body").trigger(esc); // change body to the element where you'd like to execute the escape key press.

See this working demo and the docs at jquery.com

Also note that, as stated by Christofer, this might not be working in all browsers and environments as it might be considered shady behavior that could be used in a malicious manner - just like triggering a click event on an <a> with an external href will not happen. I successfully tested this (the Esc) in Chrome, Safari, Opera, FF & IE9 though.

like image 171
m90 Avatar answered Sep 21 '22 21:09

m90


For security reasons, some browsers (not sure if all), prevent you from firing keydown-events. Please refer to this article for more info.

A quote from the article:

Safari/Chrome makes the keyCode and charCode properties read-only, so it is not possible to simulate specific keys when manually firing events.

like image 35
Christofer Eliasson Avatar answered Sep 18 '22 21:09

Christofer Eliasson