1

Client requires to programmatically press Keyboard keys like "C", "Ctrl", "Shift", "5", etc.

I have checked some APIs but only handing of key presses are available. Example :

.keypress()

Are there available functions which can mimic this behavior?

[Updated Code]

$("#input").focus();
window.crossBrowser_initKeyboardEvent("keypress", {"key": 1, "char": "!", shiftKey: true});

My goal in the updated code is to focus a textfield and trigger keypresss such that the character I want to show is shown ion the textfield. But, the above code is not working also.

Kim Honoridez
  • 917
  • 2
  • 15
  • 28
  • If you could find out why, and in what context this is required, we might be able to help . . . – Pat Dobson Feb 12 '15 at 09:53
  • possible duplicate of [Simulate JavaScript Key Events](http://stackoverflow.com/questions/596481/simulate-javascript-key-events) – Praveen Prasannan Feb 12 '15 at 10:06
  • @PatDobson: What the client wants is to be able to copy item to clipboard in Chrome by just clicking a button without using flash (just pure JS). I have checked through this but it seems not supported due to some security risks. So, client thinks that if there's a way to trigger the keyboard such that CTRL+C is pressed programmatically then it might solve this issue. – Kim Honoridez Feb 13 '15 at 03:03

2 Answers2

2

Use jquery

var e = jQuery.Event("keydown");
    e.which = 8; // # Some key code value
    $("input").trigger(e);

More reference, Also See This

Community
  • 1
  • 1
Arunprasanth K V
  • 20,733
  • 8
  • 41
  • 71
-1

If you don't want to use jQuery, this is what I recommend, paste this right into your script tags, run it, and press capital A to see a message.

document.addEventListener("keypress", function (e) 
{                                            //Start of addEventListener
       if (e.which == 65)                    //When A is pressed
                alert("A was pressed");      //Message will show
}, false);                                   //End of addEventListener
azro
  • 53,056
  • 7
  • 34
  • 70
dizad87
  • 448
  • 4
  • 15
  • 3
    The question is about firing the keydown event and not handling it, this doesn't answer the question. – cнŝdk Aug 09 '17 at 13:06