3

it is possible to generate a click event like this.

$("#elementId").trigger("click");

but I am confused how we can generate an 'enter' event similarly? I searched through internet and one way I found was,

$("#elementId").trigger("keypress",[13]);

but this is not working for me? Is this is correct? or is there any other way to do this?

Jinesh
  • 2,507
  • 2
  • 22
  • 23
  • what do you mean by "enter"? the enter key is pressed, or mouse entering the area? – jimpic May 15 '12 at 08:10
  • http://stackoverflow.com/questions/832059/definitive-way-to-trigger-keypress-events-with-jquery – Andreas Wong May 15 '12 at 08:15
  • i don't think its programatically possible to fire user-driven event like click itself, if so i could trigger the event to open ads on my site when a user visits a page similar to invoking [clickjacking](http://en.wikipedia.org/wiki/Clickjacking) and pose a security risk – optimusprime619 May 15 '12 at 08:16
  • @jimpic, certainly it was enter key press, not mouse entering area. – Jinesh May 15 '12 at 08:27
  • @optimusprime619, thanks for good piece of information. – Jinesh May 15 '12 at 08:41

4 Answers4

1

Do you mean something like:

var e = jQuery.Event("keydown");
e.which = 13; // # Some key code value for Enter
$("input").trigger(e);
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

This?

var e = $.Event("keydown", { keyCode: 13 });
$("#elementId").trigger(e);

http://api.jquery.com/category/events/event-object/

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
1

You can use the following code to trigger a Enter keypress event

var e = jQuery.Event("keydown");
e.which = 13; // # Enter key code value
$("#elementId").trigger(e);
Prasenjit Kumar Nag
  • 13,391
  • 3
  • 45
  • 57
0

your syntax is incorrect. if you need the keycode try:

$("#elementId").keypress(function(e) {
  if ( e.which == 13 ) {
     //do stuff here
   }    
});

if you just want an event once the element is focus, try the focus() syntax.

$("#elementId").focus(function(){ ... });
Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55