jQuery Keyboard Input

I was working on some jQuery today in a WordPress theme I’m working on, and I wanted to simulate a keyboard input so that I could force a jQuery plugin to work in the way I wanted it to without hacking its core.  Here’s how you do it:

  1. First figure out the e.which code for what key you want to ‘fake’ being pushed using this tool.
  2. Then create the jQuery (in your document ready or wherever you are going to use it) to simulate the keydown event
    	//create event var
    	e = jQuery.Event("keydown");
    	//set which key is being pressed
    	e.which = 40 ;
    	//trigger the event
    	jQuery("#my-element-id").trigger(e);
    

Beautiful isn’t it 🙂

Update: this may not be relevant in 2018 anymore.

One response

  1. munyah Avatar
    munyah

    wow dude thats like super simple!! thanks will give it a try!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.