Explain Codes LogoExplain Codes Logo

Definitive way to trigger keypress events with jQuery

javascript
event-triggering
jquery
cross-browser-compatibility
Nikita BarsukovbyNikita Barsukov·Feb 4, 2025
TLDR

To trigger a keypress in jQuery use .trigger() with an Event object:

var e = $.Event("keypress", { which: 97 }); // 'a' ASCII $("input").trigger(e);

This simulates an 'a' keypress event on input elements straight.

Cooking up special characters and cross-browser solutions

Special characters and cross-browser compatibility are a particular spice to handle. They don't always taste the same in every browser soup. To make them universally delicious, we set both e.which and e.keyCode:

var e = $.Event("keypress"); e.which = e.keyCode = 97; // ASCII code of 'a' $("input").trigger(e);

When dealing with special ingredients like keys that don't fire keypress events (Enter, Tab, etc.), we use the keyup event:

var e = $.Event("keyup", { keyCode: $.ui.keyCode.ENTER }); $("#target").trigger(e);

The jQuery UI sprinkles a normalization magic dust on these keycode constants, making them tastier across different browsers.

More than one way to trigger a key event

Depending on your dish, you may need to use a different spice, reciprocating keypress with keydown events:

var e = jQuery.Event('keydown', { which: 13 }); // ASCII code of Enter $('input').trigger(e); // Enter has entered the chat!

Just like in a cooking show, there's always another way to bake a cake in browser land. keydown events are often the surefire way to trigger actual keyboard input across different devices.

Key to a robust simulation dinner

  • Something's missing... Ah, key code value! Every baking simulation needs its right temperatures.
  • Did your cake come out as expected? Always double-check your event triggering methods on different ovens (browsers).
  • jQuery 1.6+ and onwards provides the sous vide machines equivalent — refined event triggering methods. Use them!

Detailed simulation techniques for the hungry coder

Got complex interactions? If you're thirsty for more, add some 'keydown' and 'keyup':

// Simulate a full key press cycle. 'Cause we appetize for more! $('input').trigger($.Event('keydown', { which: 98 })) // ASCII code of 'b' .trigger($.Event('keyup', { which: 98 })); // 'b' had enough!

We use this when we need to simulate a user completely pressing and releasing a key.

Adding spice to dynamic contexts

Adding an ingredient while the stew is still cooking? Dynamically triggering the event is as easy as pie:

$(document).on('keydown', 'input.dynamic', function(e){ e.which = 99; // secret ingredient 'c'! });

This effectively binds the keydown event to all inputs with the class dynamic, even those that sneak into the party after it started.