Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate keypress without jquery [duplicate]

I have an input field, where the user can write things. I want that, if the user press the key "1", to simulate another key press "F". So, if the user typer the character 1, in the field it will display 1f. How can i do it, without using jQuery?

like image 419
Mateus Viccari Avatar asked Jun 26 '13 14:06

Mateus Viccari


People also ask

Can JavaScript simulate key presses?

If you need keyup events too, it is also possible to simulate keyup events by changing "keydown" to "keyup" in the code snippet. This also sends the event to the entire webpage, hence the document . If you want only a specific element to receive the event, you can substitute document for the desired element.

How to create keypress event in JavaScript?

// Add event listener on keyup document. addEventListener('keyup', (event) => { var name = event. key; var code = event. code; // Alert the key name and key code on keydown alert(`Key pressed ${name} \r\n Key code value: ${code}`); }, false);

How do you trigger Keydown event in react?

If you're trying to create a keyboard event, you can make use of KeyboradEvent constructor. An enter key event can be dispatched like: const event = new KeyboardEvent('keypress', { key: 'enter', }); console. log(event) // KeyboardEvent {isTrusted: false, key: "enter", code: "", location: 0, ctrlKey: false, …}

How do you press Enter key programmatically in typescript?

You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.


1 Answers

var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent ("keypress", true, true, window,
                0, 0, 0, 0,
                13, 13); 
var canceled = !body.dispatchEvent(evt);

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/event.initKeyEvent

For Webkit-based browser the initialization might be a bit different

initKeyboardEvent(in DOMString typeArg, 
              in boolean canBubbleArg, 
              in boolean cancelableArg, 
              in views::AbstractView viewArg, 
              in DOMString keyIdentifierArg, 
              in unsigned long keyLocationArg, 
              in boolean ctrlKeyArg, 
              in boolean shiftKeyArg, 
              in boolean altKeyArg, 
              in boolean metaKeyArg, 
              in boolean altGraphKeyArg);
like image 81
Carlos Bergen Avatar answered Sep 28 '22 08:09

Carlos Bergen