How to fire pure javascript keydown event

Asked

Viewed 3,098 times

1

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

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 that will hear 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 the Enter you need to check whether the 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>

  • but for me to force running a keydown already set. ex: I have a chat it uses keydown to send msg. so I want to add value via the val() and so send via keydown (enter).

  • @Eduardoavilheiros want that when the Enter is pressed he performs a function, that’s it?

  • @Sergio, I think he wants to insert a text dynamically, via javascript, and then trigger the keydown event, like the trigger jquery.

  • @Sergio actually I have to force the fução enter via code. shoot event as Samir speak.

  • @Eduardoavilheiros I joined that in the answer

1

A working example:


// 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 reply from the following post: https://stackoverflow.com/a/20548330/407213

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);

  • this dispatchEvent(Event) only executes event I added above. but if I have 2 other default keydown event in input. how do I execute them ?

  • I edited the above answer to explain how to execute the keydown event of the HTML elements.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.