Definitive way to trigger keypress events with jQuery
To trigger a keypress in jQuery use .trigger()
with an Event
object:
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
:
When dealing with special ingredients like keys that don't fire keypress
events (Enter, Tab, etc.), we use the keyup
event:
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:
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':
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:
This effectively binds the keydown
event to all inputs with the class dynamic
, even those that sneak into the party after it started.
Was this article helpful?