How to trigger pure javascript keydown event [closed]

1

How do I trigger events via code ex: keydown , keypress and then run a function when the Enter key is pressed, with pure javascript?

    
asked by anonymous 03.01.2017 / 12:40

2 answers

2
el.addEventListener('keydown', function(){
   //código a correr aqui...
});

If you have an element in a variable you can join the .addEventListener you will listen the event you pass in the first argument, and will run the function you pass in the second argument.

To know if the key pressed was Enter you need to check if event.keyCode == 13 .

Example:

var input = document.querySelector('input');
var mostrador = document.querySelector('#mostrador');
var enviado = document.querySelector('#enviado');
input.addEventListener('keydown', function(e) {
  if (e.keyCode == 13) {
    e.preventDefault();
    return enviar(this.value);
  }
  mostrador.innerHTML = this.value.split('').reverse().join('');
});

function enviar(texto) {
  enviado.innerHTML = 'Enviado: ' + texto;
}
<section>
  <label>
    <p>Escreve algo aqui e carrega "Enter":</p>
  </label>
  <input>
</section>
<section>
  <p id="mostrador"></p>
  <p id="enviado"></p>
</section>
    
03.01.2017 / 12:42
0

An example running:


// Add um listener
document.addEventListener("nome-do-evento", function(e) {
  console.log(e.detail); // Exibe "Exemplo do evento" no console
});

// Criando o evento
var event = new CustomEvent("nome-do-evento", { "detail": "Exemplo do evento" });

// Chama o evento
document.dispatchEvent(event);

I copied this response from the following post: link

Edit:

Running a keydown event of a specific HTML element:


// Seleciona o elemento
var element = document.querySelector('input');

// Adiciona (mais um) listener para exibir no console a key 'pressionada'
element.addEventListener("keydown", function(e){ console.log(e.key) });

// Cria um objeto do evento especifico
var e = new KeyboardEvent("keydown", { key : "Q"});

// Chama o evento
element.dispatchEvent(e);

    
03.01.2017 / 13:26