How to trigger a keyboard event with a specific key

1

I need to trigger a keydown key event simulating that the user pressed the escape key.

window.addEventListener('load', init, false);

function init() {
  var input1 = document.querySelector('input[name="text1"]');
  input1.addEventListener('keydown', metodo1, false);
  var button1 = document.querySelector('input[name="button1"]');
  button1.addEventListener('click', metodo2, false);
}

function metodo1(e) {
  if (e.key == 'Escape') {
    e.target.value = '';
  }
}

function metodo2(e) {
  //aqui necesito dispara el evento de teclado keydown del
  // input1 simulando que el usuario presiono la tecla escape
  // algo mas o menos asi:
  // var event = new MouseEvent('click');
  // var element = document.querySelector('input[name="text1"]');
  // element.dispatchEvent(event);
  // pero que sea un evento de teclado que simule que se ha presionado la 
  //tecla Escape
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>
  <input type="text" name="text1">
  <input type="button" name="button1" value="presionar">

</body>

</html>
    
asked by Neyer 18.12.2017 в 17:16
source

2 answers

2

If your intention is to generate events to replace the user's input, I am afraid that it is not possible. The w3c provides mechanisms to identify if an event is generated by the user-agent (or the user through it), if it is an event created by a script then it will not execute the default controllers (you must recreate its behavior completely).

;(function() {
const ESCAPE_KEY = 'Escape'

function robotController(e)
{
    if (e.isTrusted) {
        console.warn('No eres un robot')
        e.preventDefault()
        return
    }
    if (ESCAPE_KEY == e.code) {
        console.log('Robot ha presionado ESC')
    }
}
const reI = document.querySelector('#RobotEvents')

reI.addEventListener('keypress', robotController, false)
reI.dispatchEvent(new KeyboardEvent('keypress', {key: ESCAPE_KEY, code: ESCAPE_KEY}))
}())
<input id="RobotEvents" type="text" placeholder="Prueba escribir" />

The previous code shows how to easily identify robot events through e.isTrusted , doing e.preventDefault() cancels the default controllers, that is, no text will be added to the widget. Events created via JavaScript have a e.preventDefault() implicitly.

    
answered by 18.12.2017 в 17:53
1

The logical thing would be to create a function that is called when you click on the button and when you click escape in the text field, so you do not have to simulate anything, but if you really want to simulate the event, you only have to create it and then shoot it:

window.addEventListener('load', init, false);

function init() {
  var input1 = document.querySelector('input[name="text1"]');
  input1.addEventListener('keydown', metodo1, false);
  var button1 = document.querySelector('input[name="button1"]');
  button1.addEventListener('click', metodo2, false);
}

function metodo1(e) {
  if (e.key == 'Escape') {
    e.target.value = '';
  }
  console.log(e.key)
}

function metodo2(e) {
  let event = new KeyboardEvent('keydown', { key: 'Escape'});
   var input1 = document.querySelector('input[name="text1"]');
   input1.dispatchEvent(event);
  
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>
  <input type="text" name="text1">
  <input type="button" name="button1" value="presionar">

</body>

</html>

You can find more information on the MDN website.

    
answered by 18.12.2017 в 17:35